Exemplo n.º 1
1
 public static string ObjetoSerializado(Object Objeto)
 {
     System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(Objeto.GetType());
     System.IO.StringWriter textWriter = new System.IO.StringWriter();
     x.Serialize(textWriter, Objeto);
     return textWriter.ToString();
 }
Exemplo n.º 2
0
        public Flask(ContentManager Content)
        {
            System.Xml.Serialization.XmlSerializer ax = new System.Xml.Serialization.XmlSerializer(ItemSequence.GetType());

            Stream txtReader = Microsoft.Xna.Framework.TitleContainer.OpenStream(PrinceOfPersiaGame.CONFIG_PATH_CONTENT + PrinceOfPersiaGame.CONFIG_PATH_SEQUENCES + Enumeration.Items.flask.ToString().ToUpper() + "_sequence.xml");
            //TextReader txtReader = File.OpenText(PrinceOfPersiaGame.CONFIG_PATH_CONTENT + PrinceOfPersiaGame.CONFIG_PATH_SEQUENCES + tileType.ToString().ToUpper() + "_sequence.xml");

            ItemSequence = (List<Sequence>)ax.Deserialize(txtReader);

            foreach (Sequence s in ItemSequence)
            {
                s.Initialize(Content);
            }

            //Search in the sequence the right type
            Sequence result = ItemSequence.Find((Sequence s) => s.name == Enumeration.StateTile.normal.ToString().ToUpper());

            if (result != null)
            {
                //AMF to be adjust....
                result.frames[0].SetTexture(Content.Load<Texture2D>(PrinceOfPersiaGame.CONFIG_ITEMS + result.frames[0].value));

                Texture = result.frames[0].texture;
            }

            //change statetile element
            StateTileElement stateTileElement = new StateTileElement();
            stateTileElement.state = Enumeration.StateTile.normal;
            itemState.Add(stateTileElement);

            itemAnimation.PlayAnimation(ItemSequence, itemState.Value());
        }
Exemplo n.º 3
0
        public UnityEditor.EditorBuildSettingsScene[] GetPreviousScenesToRestore()
        {
            string text = null;
            if (Application.isEditor)
            {
                text = GetTextFromTempFile(previousScenes);
            }
                
            if(text != null)
            {
                var serializer = new System.Xml.Serialization.XmlSerializer(typeof(UnityEditor.EditorBuildSettingsScene[]));
                using(var textReader = new StringReader(text))
                {
                    try 
                    {
                        return (UnityEditor.EditorBuildSettingsScene[] )serializer.Deserialize(textReader);
                    }
                    catch (System.Xml.XmlException e)
                    {
						Debug.Log (e);
                        return null;
                    }
                }
            }
                
            return null;
        }
 public static void SaveData(PlayerData data)
 {
     System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(data.GetType());
     Stream stream = File.Open("save.dat", FileMode.OpenOrCreate);
     x.Serialize(stream, data);
     stream.Close();
 }
Exemplo n.º 5
0
 public void Save()
 {
     var reader = new System.Xml.Serialization.XmlSerializer(typeof(List<Words>));
     var file = new FileStream("words.xml", FileMode.Create);
     reader.Serialize(file, LocalWords._words);
     file.Close();
 }
Exemplo n.º 6
0
 private static object DeserializeMessage_XML(string cmd, Type cmdType) {
   using( StringReader stringReader = new StringReader(cmd) )
   using( XmlTextReader xmlTextReader = new XmlTextReader(stringReader) ) {
     System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(cmdType);
     return x.Deserialize(xmlTextReader);
   }
 }
        public static object Deserialize(string xmlContent, string serializerType)
        {
            object returnValue = null;
            SerializerTypes serializerTypeValue;
            Type instanceType;
            GetSerializerDetails(serializerType, out serializerTypeValue, out instanceType);

            if (serializerTypeValue == SerializerTypes.XmlSerializer)
            {
                StringReader sww = new StringReader(xmlContent);
                XmlReader reader = XmlReader.Create(sww);
                System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(instanceType);
                returnValue = serializer.Deserialize(reader);
            }
            else if (serializerTypeValue == SerializerTypes.XmlObjectSerializer)
            {
                XmlObjectSerializer serializer = new XmlObjectSerializer();
                returnValue = serializer.Deserialize(xmlContent, true);
            }
            else
            {
                if (instanceType == typeof(string))
                {
                    returnValue = xmlContent;
                }
                else
                {
                    var method = instanceType.GetMethod("Parse", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
                    returnValue = method.Invoke(null, new object[] { xmlContent });
                }
            }
            return returnValue;
        }
        private void btnSubmit_Click(object sender, EventArgs e)
        {
            //string xml;
               Contact contact = new Contact();

            contact.companyName = txtCompany.Text;
            contact.firstName = txtFName.Text;
            contact.middleName = txtMName.Text;
            contact.lastName = txtLName.Text;
            contact.liscence = txtLicense.Text;
            contact.phone = txtPhone.Text;
            contact.cell = txtCell.Text;
            contact.email = txtEmail.Text;
            contact.buildingLiscence = txtBuildingLicense.Text;
            contact.streetNumber = txtStreetNumber.Text;
            contact.streetName = txtStreetName.Text;
            contact.type = txtType.Text;
            contact.streetName2 = txtStreetName2.Text;
            contact.city = txtCity.Text;
            contact.state = txtState.Text;
            contact.zip = txtZip.Text;
            System.IO.StreamWriter file = new System.IO.StreamWriter(@"Contact.xml");
            System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(contact.GetType());
            x.Serialize(file, contact);
            file.Close();
        }
Exemplo n.º 9
0
 public static List<SolutionInfo> GetSolutionPriorityList()
 {
     var dte = XFeaturesPackage.DTE();
     var slnpriorityfile = dte.Solution.FullName + ".xml";
     var newlist = new List<SolutionInfo>();
     if(File.Exists(slnpriorityfile))
     {
         using (System.IO.StreamReader reader = new System.IO.StreamReader(slnpriorityfile))
         {
             System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(Container));
             var cnt = (Container)serializer.Deserialize(reader);
             if (cnt != null)
             {
                 GetValidProjects(cnt.Items,ref newlist);
                 if (newlist.Any() == false)
                 {
                     return cnt.Items;
                 }
             }
         }
     }
     else
     {
         GetValidProjects(new List<SolutionInfo>(),ref newlist);
     }
     return newlist;
 }
Exemplo n.º 10
0
        private void LoadTestCredential()
        {
            string path = @"C:\Temp\AmazonAwsS3Test.xml";
            Models.AwsCredential credential;
            var xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(Models.AwsCredential));

            if (!System.IO.File.Exists(path))
            {
                //Cria um arquivo xml novo, se já não existir um
                credential = new Models.AwsCredential();
                credential.User = string.Empty;
                credential.AccessKeyId = string.Empty;
                credential.SecretAccessKey = string.Empty;
                credential.Region = string.Empty;

                using (var streamWriter = new System.IO.StreamWriter(path))
                {
                    xmlSerializer.Serialize(streamWriter, credential);
                }
            }

            //Carrega o xml
            using (var streamReader = new System.IO.StreamReader(path))
            {
                credential = (Models.AwsCredential)xmlSerializer.Deserialize(streamReader);
            }

            txtAccessKeyId.Text = credential.AccessKeyId;
            txtSecretAccessKey.Text = credential.SecretAccessKey;
            txtRegion.Text = credential.Region;
        }
Exemplo n.º 11
0
		void LoadFromFile()
		{
			var reader = new System.Xml.Serialization.XmlSerializer(typeof(List<string>));
			var file = new System.IO.StreamReader(@"words.xml");
			words = new List<string>();
			words = (List<string>)reader.Deserialize(file);
		}
Exemplo n.º 12
0
 private List<Record> GetHigtscore()
 {
     System.Xml.Serialization.XmlSerializer reader = new System.Xml.Serialization.XmlSerializer(typeof(List<Record>));
     System.IO.StreamReader file = new System.IO.StreamReader("Records.xml");
     _records = (List<Record>)reader.Deserialize(file);
     return _records;
 }
        //Loads a environment from an XML file and initializes it
        public static ExperimentWrapper load(string name)
        {
            System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(ExperimentWrapper));
            TextReader infile = new StreamReader(name);
            ExperimentWrapper e = (ExperimentWrapper)x.Deserialize(infile);
            infile.Close();

            //TODO include LEO

            //Determine the number of CPPN inputs and outputs automatically
            //if (e.experiment.homogeneousTeam)
            //    e.experiment.inputs = 4;
            //else
            //    e.experiment.inputs = 5;

            //if (e.experiment.adaptableANN)
            //{
            //    if (e.experiment.modulatoryANN) e.experiment.outputs = 8; else e.experiment.outputs = 7;
            //}
            //else
            //    e.experiment.outputs = 2;

            //TODO maybe include			e.experiment.initialize();
            return e;
        }
Exemplo n.º 14
0
        //[DebuggerHidden]
        public override bool Init()
        {
            loopratehz = 1;

            if (File.Exists(statsfile))
            {
                try
                {
                    System.Xml.Serialization.XmlSerializer reader = new System.Xml.Serialization.XmlSerializer(statsoverall.GetType());

                    var file = new System.IO.StreamReader(statsfile);

                    statsoverall = (whattostat)reader.Deserialize(file);

                    file.Close();
                }
                catch { }
            }

            MainV2.instance.Invoke((Action)
                delegate
                {

            System.Windows.Forms.ToolStripMenuItem men = new System.Windows.Forms.ToolStripMenuItem() { Text = "Stats" };
            men.Click += men_Click;
            Host.FDMenuMap.Items.Add(men);
            });

            statsoverall.appstarts++;

            return true;
        }
Exemplo n.º 15
0
        public void InitializeTwitter()
        {
            try
            {
                System.Xml.Serialization.XmlSerializer serializer =
                    new System.Xml.Serialization.XmlSerializer(typeof(saveSettings));
                System.IO.FileStream fs = new System.IO.FileStream(
                    @"settings.xml", System.IO.FileMode.Open);
                saveSettings setting = (saveSettings)serializer.Deserialize(fs);
                fs.Close();
                textBox1.Enabled = false;
                //accToken = setting.AccToken;
                token.AccessToken = setting.AccToken;
                //accTokenSec = setting.AccTokenSec;
                token.AccessTokenSecret = setting.AccTokenSec;

                var Stream = new TwitterStream(token, "Feedertter", null);

                StatusCreatedCallback statusCreatedCallback = new StatusCreatedCallback(StatusCreatedCallback);
                RawJsonCallback rawJsonCallback = new RawJsonCallback(RawJsonCallback);

                Stream.StartUserStream(null, null,
                    /*(x) => { label1.Text += x.Text; }*/
                    statusCreatedCallback,
                    null, null, null, null, rawJsonCallback);
            }
            catch
            {
                Process.Start(OAuthUtility.BuildAuthorizationUri(req.Token).ToString());
            }

            //Process.Start(OAuthUtility.BuildAuthorizationUri(req.Token).ToString());
        }
Exemplo n.º 16
0
 public void Serialize(string filename)
 {
     System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(this.GetType());
     StreamWriter writer = new StreamWriter(filename);
     x.Serialize(writer, this);
     writer.Close();
 }
Exemplo n.º 17
0
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            container.Register(
                Component.For<Project>().UsingFactoryMethod<Project>(kernel => {
                    var args = Environment.GetCommandLineArgs();
                    var assembler = kernel.Resolve<ProjectAssembler>();
                    var deserializer = new System.Xml.Serialization.XmlSerializer(typeof(ProjectDTO));
                    ProjectDTO dto = null;

                    try
                    {
                        using (TextReader reader = new StreamReader(args[1]))
                            dto = (ProjectDTO)deserializer.Deserialize(reader);
                    }
                    catch (Exception ex)
                    {
                        // halt application (not currently in a message loop)
                        // TODO: need to inform the user that we couldn't load the project: this is why
                        // we shouldn't have this logic in the installer, we need to farm it out to something
                        // else (plus we'll get a more responsive application as it'll load the UI immediately)
                        Environment.Exit(-1);
                    }

                    return assembler.Restore(dto);
                }),
                Component.For<IConfiguration>()
                    .UsingFactoryMethod<IConfiguration>(kernel => kernel.Resolve<Project>().Configuration),
                Component.For<IList<ISubject>>()
                    .UsingFactoryMethod(kernel => kernel.Resolve<IConfiguration>())
            );
        }
Exemplo n.º 18
0
 public static RSAParameters ReadKeyFromString(string key)
 {
     StringReader sr = new System.IO.StringReader(key);
     var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
     RSAParameters k = (RSAParameters)xs.Deserialize(sr);
     return k;
 }
Exemplo n.º 19
0
        /// <summary>
        /// Gets the value of a parameter
        /// </summary>
        /// <param name="o">the parameter</param>
        /// <returns>string or serialised xml representation of the parameter</returns>
        private static string GetParamValue(object o)
        {
            string paramDetails = String.Empty;
            if (o != null)
            {
                try
                {
                    Type t = o.GetType();
                    if (t.IsValueType || t.IsSerializable == false || t.Name == "String")
                    {
                        paramDetails = String.Format("{0} : {1}", t, o);
                    }
                    else
                    {
                        System.Xml.Serialization.XmlSerializer s = new System.Xml.Serialization.XmlSerializer(t);
                        using (System.IO.StringWriter sw = new System.IO.StringWriter())
                        {
                            s.Serialize(sw, o);
                            paramDetails = String.Format("{0} : {1}", t, sw);
                        }
                    }
                }
                catch
                {
                    paramDetails = o.ToString();
                }
            }

            return paramDetails;
        }
Exemplo n.º 20
0
        public static object DeSerialize(string sXML, Type ObjectType)
        {
            System.IO.StringReader oStringReader = null;
            System.Xml.Serialization.XmlSerializer oXmlSerializer = null;
            object oObject = null;

            // -----------------------------------------------------------------------------------------------------------------------
            // Hvis mangler info, lage tom
            // -----------------------------------------------------------------------------------------------------------------------
            if (sXML == string.Empty)
            {
                Type[] types = new Type[-1 + 1];
                ConstructorInfo info = ObjectType.GetConstructor(types);
                object targetObject = info.Invoke(null);
                if (targetObject == null)
                    return null;
                return targetObject;
            }

            // -----------------------------------------------------------------------------------------------------------------------
            // Gjøre om fra XML til objekt
            // -----------------------------------------------------------------------------------------------------------------------
            oStringReader = new System.IO.StringReader(sXML);
            oXmlSerializer = new System.Xml.Serialization.XmlSerializer(ObjectType);
            oObject = oXmlSerializer.Deserialize(oStringReader);

            return oObject;
        }
Exemplo n.º 21
0
        public static AltaCache Read(string file)
        {
            if (!File.Exists(file))
            {
                Write(file, new AltaCache());
                return new AltaCache();
            }
            else
            {
                FileInfo inf = new FileInfo(file);
                while (inf.IsFileLocked()) { Console.WriteLine("Wait..."); };
                try
                {
                    using (Stream s = File.Open(file, FileMode.Open))
                    {
                        System.Xml.Serialization.XmlSerializer reader = new System.Xml.Serialization.XmlSerializer(typeof(AltaCache));
                        return (AltaCache)reader.Deserialize(s);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.GetBaseException().ToString());
                    return new AltaCache();
                }

            }
        }
Exemplo n.º 22
0
 public static void Write(string file, AltaCache overview)
 {
     if (string.IsNullOrEmpty(file))
         throw new Exception("File Not Empty");
     System.Xml.Serialization.XmlSerializer writer =
     new System.Xml.Serialization.XmlSerializer(typeof(AltaCache));
     System.Xml.XmlWriterSettings setting = new System.Xml.XmlWriterSettings();
     setting.Encoding = Encoding.UTF8;
     setting.CloseOutput = true;
     setting.NewLineChars = "\r\n";
     setting.Indent = true;
     if (!File.Exists(file))
     {
         using (Stream s = File.Open(file, FileMode.OpenOrCreate))
         {
             System.Xml.XmlWriter tmp = System.Xml.XmlWriter.Create(s, setting);
             writer.Serialize(tmp, overview);
         }
     }
     else
     {
         using (Stream s = File.Open(file, FileMode.Truncate))
         {
             System.Xml.XmlWriter tmp = System.Xml.XmlWriter.Create(s, setting);
             writer.Serialize(tmp, overview);
         }
     }
 }
Exemplo n.º 23
0
        public Chomper(RoomNew room, ContentManager Content, Enumeration.TileType tileType, Enumeration.StateTile state, Enumeration.TileType NextTileType__1)
        {
            base.room = room;

            nextTileType = NextTileType__1;
            System.Xml.Serialization.XmlSerializer ax = new System.Xml.Serialization.XmlSerializer(tileSequence.GetType());

            Stream txtReader = Microsoft.Xna.Framework.TitleContainer.OpenStream(PrinceOfPersiaGame.CONFIG_PATH_CONTENT + PrinceOfPersiaGame.CONFIG_PATH_SEQUENCES + tileType.ToString().ToUpper() + "_sequence.xml");

            tileSequence = (List<Sequence>)ax.Deserialize(txtReader);

            foreach (Sequence s in tileSequence)
            {
                s.Initialize(Content);
            }

            //Search in the sequence the right type
            //Sequence result = tileSequence.Find((Sequence s) => s.name.ToUpper() == state.ToString().ToUpper());
            Sequence result = tileSequence.Find((Sequence s) => s.name == state.ToString().ToUpper());

            if (result != null)
            {
                result.frames[0].SetTexture(Content.Load<Texture2D>(PrinceOfPersiaGame.CONFIG_TILES[0] + result.frames[0].value));

                collision = result.collision;
                Texture = result.frames[0].texture;
            }
            Type = tileType;

            //change statetile element
            tileState.Value().state = state;
            tileAnimation.PlayAnimation(tileSequence, tileState.Value());
        }
Exemplo n.º 24
0
        public static void Serialize(object obj, TextWriter output)
        {
            Debug.Assert(obj != null);
            Debug.Assert(output != null);

            #if !NET_1_0 && !NET_1_1
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.NewLineOnAttributes = true;
            settings.CheckCharacters = false;
            settings.OmitXmlDeclaration = true;
            XmlWriter writer = XmlWriter.Create(output, settings);
            #else
            XmlTextWriter writer = new XmlTextWriter(output);
            writer.Formatting = Formatting.Indented;
            #endif

            try
            {
                SystemXmlSerializer serializer = new SystemXmlSerializer(obj.GetType());
                serializer.Serialize(writer, obj);
                writer.Flush();
            }
            finally
            {
                writer.Close();
            }
        }
        public static void Serialize(object instance, out string xmlContent, out string serializerType)
        {
            SerializerTypes serializerTypeValue = SerializerTypes.Primitive;
            xmlContent = string.Empty;
            Type instanceType = typeof(object);
            if (instance != null)
            {
                if (instanceType.IsPrimitive || instanceType == typeof(string))
                {
                    xmlContent = string.Format("<{0}>{1}</{0}>", instanceType.Name, instance);
                }
                else if (instanceType.GetCustomAttributes(typeof(SerializableAttribute), true).FirstOrDefault() != null)
                {
                    serializerTypeValue = SerializerTypes.XmlSerializer;
                    StringWriter sww = new StringWriter();
                    XmlWriter writer = XmlWriter.Create(sww);
                    System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(instanceType);
                    serializer.Serialize(sww, instanceType);
                    xmlContent = sww.ToString();
                }
                else
                {
                    serializerTypeValue = SerializerTypes.XmlObjectSerializer;
                    XmlObjectSerializer serializer = new XmlObjectSerializer();
                    xmlContent = serializer.Serialize(instance, instanceType).OuterXml;
                }
            }

            serializerType = string.Format(SerializerTypeFormat, serializerTypeValue, instanceType.AssemblyQualifiedName);
        }
Exemplo n.º 26
0
        static void Main(string[] args)
        {
            System.Xml.Serialization.XmlSerializer sr = new System.Xml.Serialization.XmlSerializer(typeof(Config));
            if (!System.IO.File.Exists(AppDomain.CurrentDomain.BaseDirectory + "config.xml"))
            {
                Config config = new Config() {id=1, WirelessComPort = "Com14", TouhPanelComPort = "Com18",IOComPort="Com12" };
            
                sr.Serialize(System.IO.File.Create(AppDomain.CurrentDomain.BaseDirectory + "config.xml"), config);
                Console.WriteLine("please modify the config.xml");
             //   Console.ReadKey();
                Environment.Exit(-1);
            }
            else
            {
                config = sr.Deserialize(System.IO.File.OpenRead(AppDomain.CurrentDomain.BaseDirectory + "config.xml")) as Config;

                if (config == null)
                {
                    Console.WriteLine("config.xml  reading error!");
                    Environment.Exit(-1);
                }
            }
            controller = new Controller(config.id,config.WirelessComPort,config.TouhPanelComPort,config.IOComPort);

            
        }
Exemplo n.º 27
0
 public void SaveXML(ConfigureXml config)
 {
     System.Xml.Serialization.XmlSerializer writer = new System.Xml.Serialization.XmlSerializer(typeof(ConfigureXml));
     System.IO.StreamWriter file = new System.IO.StreamWriter(@"AppConfig.xml");
     writer.Serialize(file, config);
     file.Close();
 }
Exemplo n.º 28
0
        private void Button_ClickSave(object sender, RoutedEventArgs e)
        {
            //WIP
            string CartBox = ArtBox.SelectedItems.ToString();
            string Comboselectedmonth = DateBoxMonth.SelectedItem.ToString();
            string Comboselectedyear = DateBoxYear.SelectedItem.ToString();
            string Agynentxt = GyneBox.Text.ToString();
            string Aworkertxt = WorkerBox.Text.ToString();
            string Asoldiertxt = SoldierBox.Text.ToString();

            Colony ColonyOne = new Colony();
            ColonyOne.Cname = NameBox.Text;
            ColonyOne.Cart = CartBox;
            ColonyOne.Cnote = NoteBox.Text;

            ColonyOne.Cgdatummonth = Comboselectedmonth;
            ColonyOne.Cgdatumyear = Comboselectedyear;

            ColonyOne.Agynen = Agynentxt;
            ColonyOne.Aworker = Aworkertxt;
            ColonyOne.Asoldiers = Asoldiertxt;

            //nn to check if folder exists, "System.IO.Directory.CreateDirectory" does that for us
            string mydocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            System.IO.Directory.CreateDirectory(mydocs + "/AntManager");

            System.Xml.Serialization.XmlSerializer writer = new System.Xml.Serialization.XmlSerializer(typeof(Colony));

            var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "/AntManager/AntManagerSaveFile.xml";
            System.IO.FileStream file = System.IO.File.Create(path);

            writer.Serialize(file, ColonyOne);
            file.Close();
        }
Exemplo n.º 29
0
 public object Deserialize(System.IO.Stream stream, Type type)
 {
     System.Xml.Serialization.XmlSerializer serializer =
         new System.Xml.Serialization.XmlSerializer(type);
     stream.Position = 0;
     return serializer.Deserialize(stream);
 }
Exemplo n.º 30
0
        protected override void OnCreate (Bundle bundle)
        {
            base.OnCreate (bundle);

            //
            // Get the person object from the intent
            //
            Person person;
            if (Intent.HasExtra ("Person")) {
                var serializer = new System.Xml.Serialization.XmlSerializer (typeof (Person));
                var personBytes = Intent.GetByteArrayExtra ("Person");
                person = (Person)serializer.Deserialize (new MemoryStream (personBytes));
            } else {
                person = new Person ();
            }

            //
            // Load the View Model
            //
            viewModel = new PersonViewModel (person, Android.Application.SharedFavoritesRepository);
            viewModel.PropertyChanged += HandleViewModelPropertyChanged;

            //
            // Setup the UI
            //
            ListView.Divider = null;
            ListAdapter = new PersonAdapter (viewModel);

            Title = person.SafeDisplayName;
        }
        public async Task <IActionResult> Index(List <IFormFile> files)
        {
            long size = files.Sum(f => f.Length);

            var filePaths          = new List <string>();
            var orderList          = new List <Models.TestOrder.Orders>();
            var tradingPartnerList = new List <string>();
            var totalLineItemsList = new List <int>();
            var totalAmountList    = new List <decimal>();

            foreach (var formFile in files)
            {
                if (formFile.Length > 0)
                {
                    var filePath = Path.GetTempFileName();
                    filePaths.Add(filePath);

                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        await formFile.CopyToAsync(stream);
                    }
                }
            }

            foreach (var filePath in filePaths)
            {
                System.Xml.Serialization.XmlSerializer s = new System.Xml.Serialization.XmlSerializer(typeof(Models.TestOrder.Orders));

                using (StreamReader sr = new StreamReader(filePath))
                {
                    Models.TestOrder.Orders o = (Models.TestOrder.Orders)s.Deserialize(sr);

                    int     lineItemCount = o.Order.Summary.TotalLineItemNumber;
                    decimal totalAmount   = o.Order.Summary.TotalAmount;

                    int matchingTradingPartnerIndex = orderList.FindIndex(x => x.Order.Header.OrderHeader.TradingPartnerId
                                                                          == o.Order.Header.OrderHeader.TradingPartnerId);

                    if (matchingTradingPartnerIndex == -1)
                    {
                        tradingPartnerList.Add(o.Order.Header.OrderHeader.TradingPartnerId);
                        totalLineItemsList.Add(o.Order.Summary.TotalLineItemNumber);
                        totalAmountList.Add(o.Order.Summary.TotalAmount);
                    }
                    else
                    {
                        int m = tradingPartnerList.FindIndex(x => x == o.Order.Header.OrderHeader.TradingPartnerId);
                        totalLineItemsList[m] += lineItemCount;
                        totalAmountList[m]    += totalAmount;
                    }

                    orderList.Add(o);
                }
            }

            List <Models.TestOrder.Orders> sortedOrderList = orderList.OrderBy(x => x.Order.Header.OrderHeader.TradingPartnerId).ToList();
            List <string>  sortedTradingPartnerList        = tradingPartnerList.OrderBy(x => x).ToList();
            List <int>     sortedTotalLineItemsList        = new List <int>();
            List <decimal> sortedTotalAmountList           = new List <decimal>();

            foreach (string t in sortedTradingPartnerList)
            {
                int m = tradingPartnerList.FindIndex(x => x == t);
                sortedTotalLineItemsList.Add(totalLineItemsList[m]);
                sortedTotalAmountList.Add(totalAmountList[m]);
            }

            //ViewData["totalLineItemsList"] = sortedTotalLineItemsList;
            //ViewData["totalAmountList"] = sortedTotalAmountList;

            TempData["orderList"]          = JsonConvert.SerializeObject(sortedOrderList);
            TempData["totalLineItemsList"] = JsonConvert.SerializeObject(sortedTotalLineItemsList);
            TempData["totalAmountList"]    = JsonConvert.SerializeObject(sortedTotalAmountList);

            return(Redirect("Home/OrderDisplay"));
        }
Exemplo n.º 32
0
        protected void BuscarButton_Click(object sender, EventArgs e)
        {
            if (Funciones.SessionTimeOut(Session))
            {
                Response.Redirect("~/SessionTimeout.aspx");
            }
            else
            {
                try
                {
                    MensajeLabel.Text = "";
                    bool                         monedasExtranjeras = false;
                    Entidades.Sesion             sesion             = (Entidades.Sesion)Session["Sesion"];
                    List <Entidades.Comprobante> listaC             = new List <Entidades.Comprobante>();

                    List <Entidades.Estado> estados = new List <Entidades.Estado>();
                    Entidades.Estado        es      = new Entidades.Estado();
                    es.Id = "Vigente";
                    estados.Add(es);
                    Entidades.Persona persona          = new Entidades.Persona();
                    Entidades.NaturalezaComprobante nc = new Entidades.NaturalezaComprobante();
                    nc.Id  = "Compra";
                    listaC = RN.Comprobante.ListaFiltradaIvaYMovimientos(estados, FechaDesdeTextBox.Text, FechaHastaTextBox.Text, persona, nc, false, "", sesion);

                    Entidades.IvaCompras ivaCompras = new Entidades.IvaCompras();
                    ivaCompras.Cuit       = sesion.Cuit.Nro;
                    ivaCompras.PeriodoDsd = FechaDesdeTextBox.Text.Substring(6, 2) + "/" + FechaDesdeTextBox.Text.Substring(4, 2) + "/" + FechaDesdeTextBox.Text.Substring(0, 4);
                    ivaCompras.PeriodoHst = FechaHastaTextBox.Text.Substring(6, 2) + "/" + FechaHastaTextBox.Text.Substring(4, 2) + "/" + FechaHastaTextBox.Text.Substring(0, 4);

                    System.Xml.Serialization.XmlSerializer x;
                    byte[] bytes;
                    System.IO.MemoryStream ms;
                    FeaEntidades.InterFacturas.lote_comprobantes lote;

                    ivaCompras.IvaComprasComprobantes = new List <Entidades.IvaComprasComprobantes>();

                    listaTotXIMP = new List <Entidades.IvaComprasTotXImpuestos>();
                    listaTotXIVA = new List <Entidades.IvaComprasTotXIVA>();
                    foreach (Entidades.Comprobante comprobante in listaC)
                    {
                        if (!(comprobante.NroDoc == sesion.Cuit.Nro && comprobante.NaturalezaComprobante.Id == "Compra"))
                        {
                            Entidades.IvaComprasComprobantes icc = new Entidades.IvaComprasComprobantes();
                            icc.PtoVta         = comprobante.NroPuntoVta.ToString();
                            icc.TipoComp       = comprobante.TipoComprobante.Descr;
                            icc.NroComp        = comprobante.Nro.ToString();
                            icc.NroDoc         = comprobante.NroDoc.ToString();
                            icc.TipoCompCodigo = comprobante.TipoComprobante.Id.ToString();
                            icc.RazSoc         = comprobante.RazonSocial;
                            if (comprobante.Documento.Tipo.Id != "99")
                            {
                                icc.TipoDoc = comprobante.DescrTipoDoc;
                            }
                            else
                            {
                                if (icc.RazSoc == "")
                                {
                                    icc.TipoDoc = "Sin identificar/compra global";
                                }
                                else
                                {
                                    icc.TipoDoc = "";
                                }
                            }

                            double signo = 1;
                            if (("/3/8/13/").IndexOf("/" + icc.TipoCompCodigo + "/") != -1)
                            {
                                signo = -1;
                            }

                            icc.ImporteTotal = comprobante.Importe * signo;
                            icc.FechaEmi     = comprobante.Fecha.ToString("dd/MM/yyyy");

                            lote = new FeaEntidades.InterFacturas.lote_comprobantes();
                            x    = new System.Xml.Serialization.XmlSerializer(lote.GetType());

                            comprobante.Request = comprobante.Request.Replace("iso-8859-1", "utf-16");
                            bytes = new byte[comprobante.Request.Length * sizeof(char)];
                            System.Buffer.BlockCopy(comprobante.Request.ToCharArray(), 0, bytes, 0, bytes.Length);
                            ms = new System.IO.MemoryStream(bytes);
                            ms.Seek(0, System.IO.SeekOrigin.Begin);
                            lote = (FeaEntidades.InterFacturas.lote_comprobantes)x.Deserialize(ms);

                            icc.Exento    = lote.comprobante[0].resumen.importe_operaciones_exentas * signo;
                            icc.NoGravado = lote.comprobante[0].resumen.importe_total_concepto_no_gravado * signo;
                            icc.Gravado   = lote.comprobante[0].resumen.importe_total_neto_gravado * signo;
                            double otrosImp = Math.Round(lote.comprobante[0].resumen.importe_total_ingresos_brutos + lote.comprobante[0].resumen.importe_total_impuestos_nacionales + lote.comprobante[0].resumen.importe_total_impuestos_municipales + lote.comprobante[0].resumen.importe_total_impuestos_internos, 2);
                            icc.OtrosImp = otrosImp * signo;
                            icc.Iva      = lote.comprobante[0].resumen.impuesto_liq * signo;

                            icc.Moneda = lote.comprobante[0].resumen.codigo_moneda;
                            if (icc.Moneda != "PES")
                            {
                                monedasExtranjeras = true;
                            }
                            icc.Cambio   = lote.comprobante[0].resumen.tipo_de_cambio;
                            icc.Concepto = lote.comprobante[0].cabecera.informacion_comprobante.codigo_concepto.ToString();
                            if (lote.comprobante[0].resumen.importes_moneda_origen != null)
                            {
                                icc.ImporteTotalME = lote.comprobante[0].resumen.importes_moneda_origen.importe_total_factura * signo;
                            }
                            ivaCompras.IvaComprasComprobantes.Add(icc);

                            //Totales por Impuestos y Totales por alicuota de IVA y concepto
                            ivaCompras.IvaComprasTotXImpuestos = new List <Entidades.IvaComprasTotXImpuestos>();
                            ivaCompras.IvaComprasTotXIVA       = new List <Entidades.IvaComprasTotXIVA>();
                            if (lote.comprobante[0].resumen.impuestos != null)
                            {
                                for (int z = 0; z < lote.comprobante[0].resumen.impuestos.Length; z++)
                                {
                                    double importe = lote.comprobante[0].resumen.impuestos[z].importe_impuesto * signo;
                                    listaTotIVAxComprobante = new List <Entidades.IvaComprasTotXIVA>();
                                    if (lote.comprobante[0].resumen.impuestos[z].codigo_impuesto == 1)
                                    {
                                        string concepto      = lote.comprobante[0].cabecera.informacion_comprobante.codigo_concepto.ToString();
                                        double alicuota      = lote.comprobante[0].resumen.impuestos[z].porcentaje_impuesto;
                                        double baseImponible = lote.comprobante[0].resumen.impuestos[z].base_imponible * signo;
                                        if (lote.comprobante[0].resumen.impuestos[z].base_imponible == 0)
                                        {
                                            if (lote.comprobante[0].detalle.linea == null || lote.comprobante[0].detalle.linea[0] == null)
                                            {
                                                //Si no hay renglones uso este método de cálculo para obtener la base imponible.
                                                baseImponible = Math.Round((lote.comprobante[0].resumen.impuestos[z].importe_impuesto * 100) / lote.comprobante[0].resumen.impuestos[z].porcentaje_impuesto, 2) * signo;
                                            }
                                            else if (lote.comprobante[0].cabecera.informacion_comprobante.tipo_de_comprobante == 6 || lote.comprobante[0].cabecera.informacion_comprobante.tipo_de_comprobante == 7 || lote.comprobante[0].cabecera.informacion_comprobante.tipo_de_comprobante == 8)
                                            {
                                                //Si hay renglones y es un comprobante 'B' también uso este método de cálculo para obtener la base imponible.
                                                baseImponible = Math.Round((lote.comprobante[0].resumen.impuestos[z].importe_impuesto * 100) / lote.comprobante[0].resumen.impuestos[z].porcentaje_impuesto, 2) * signo;
                                            }
                                            else
                                            {
                                                //Si hay reglones, obtengo la base imponible sumando los renglones de detalle del comprobante según corresponda.
                                                baseImponible = 0;
                                                for (int k = 0; k < lote.comprobante[0].detalle.linea.Length; k++)
                                                {
                                                    if (lote.comprobante[0].detalle.linea[k].indicacion_exento_gravado != null && lote.comprobante[0].detalle.linea[k].indicacion_exento_gravado.Trim().ToUpper() == "G" && lote.comprobante[0].detalle.linea[k].alicuota_iva == alicuota)
                                                    {
                                                        baseImponible += Math.Round(lote.comprobante[0].detalle.linea[k].importe_total_articulo, 2) * signo;
                                                    }
                                                }
                                                //Verificar el impuesto IVA que no exista mas de una vez la misma alicuota.
                                                List <Entidades.IvaComprasTotXIVA> listaAux = listaTotIVAxComprobante.FindAll(delegate(Entidades.IvaComprasTotXIVA txi)
                                                {
                                                    return(txi.Concepto == concepto && txi.Alicuota == alicuota);
                                                });
                                                if (listaAux.Count == 0)
                                                {
                                                    TotalesIVAXComprobante(concepto, alicuota, baseImponible, importe);
                                                }
                                                else
                                                {
                                                    //Comprobante con alícuota repetida.
                                                }
                                            }
                                        }
                                        TotalesXIVA(concepto, alicuota, baseImponible, importe);
                                        TotalesXImpuestos("IVA", importe);
                                    }
                                    else if (lote.comprobante[0].resumen.impuestos[z].codigo_impuesto == 2)
                                    {
                                        TotalesXImpuestos("Impuestos Internos", importe);
                                    }
                                    else if (lote.comprobante[0].resumen.impuestos[z].codigo_impuesto == 3)
                                    {
                                        TotalesXImpuestos("Otros Impuestos", importe);
                                    }
                                    else if (lote.comprobante[0].resumen.impuestos[z].codigo_impuesto == 4)
                                    {
                                        TotalesXImpuestos("Impuestos Nacionales", importe);
                                    }
                                    else if (lote.comprobante[0].resumen.impuestos[z].codigo_impuesto == 5)
                                    {
                                        TotalesXImpuestos("Impuestos Municipales", importe);
                                    }
                                    else if (lote.comprobante[0].resumen.impuestos[z].codigo_impuesto == 6)
                                    {
                                        TotalesXImpuestos("Ingresos Brutos", importe);
                                    }
                                }
                            }
                        }
                    }
                    if (ivaCompras.IvaComprasComprobantes.Count != 0)
                    {
                        if (listaTotXIMP.Count != 0)
                        {
                            ivaCompras.IvaComprasTotXImpuestos = listaTotXIMP;
                        }
                        else
                        {
                            //Para arreglar bug en towebs.
                            Entidades.IvaComprasTotXImpuestos totXimp = new Entidades.IvaComprasTotXImpuestos();
                            totXimp.Descr        = "";
                            totXimp.ImporteTotal = 0;
                            ivaCompras.IvaComprasTotXImpuestos.Add(totXimp);
                        }
                        if (listaTotXIVA.Count != 0)
                        {
                            ivaCompras.IvaComprasTotXIVA = listaTotXIVA;
                        }
                        else
                        {
                            //Para arreglar bug en towebs.
                            Entidades.IvaComprasTotXIVA totXiva = new Entidades.IvaComprasTotXIVA();
                            totXiva.Concepto     = "";
                            totXiva.Alicuota     = 0;
                            totXiva.ImporteNG    = 0;
                            totXiva.ImporteTotal = 0;
                            ivaCompras.IvaComprasTotXIVA.Add(totXiva);
                        }
                    }
                    Session["formatoRptExportar"] = FormatosRptExportarDropDownList.SelectedValue;
                    Session["mostrarFechaYHora"]  = FechaYHoraCheckBox.Checked;
                    Session["monedasExtranjeras"] = monedasExtranjeras;
                    if (ivaCompras.IvaComprasComprobantes.Count != 0)
                    {
                        Session["ivaCompras"] = ivaCompras;
                        Response.Redirect("~/Facturacion/Electronica/Reportes/IvaComprasWebForm.aspx", true);
                    }
                    else
                    {
                        MensajeLabel.Text = "No hay información.";
                    }
                }
                catch (System.Threading.ThreadAbortException)
                {
                    Trace.Warn("Thread abortado");
                }
                catch (Exception ex)
                {
                    WebForms.Excepciones.Redireccionar(ex, "~/NotificacionDeExcepcion.aspx");
                }
            }
        }
Exemplo n.º 33
0
        private void FileSave_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.SaveFileDialog dialog = new Microsoft.Win32.SaveFileDialog();

            dialog.Filter = FilterTxt + "|" +
                            FilterJson + "|" +
                            FilterXml + "|" +
                            FilterSoap + "|" +
                            FilterBinary;

            dialog.FilterIndex = 1;

            bool?dialogResult = dialog.ShowDialog();

            if (dialogResult == true)
            {
                string filePath = dialog.FileName;
                if (System.IO.File.Exists(filePath))
                {
                    System.IO.File.Delete(filePath);
                }

                // get content from UI control
                string content = "";

                // determine which format the user want to save as
                if (dialog.FilterIndex == 1)
                {
                    // write as txt
                    System.IO.StringWriter writer = new System.IO.StringWriter();
                    List <TodoTask>        items  = new List <TodoTask>();
                    foreach (var item in this.TodoTaskListView.Items)
                    {
                        items.Add(item as TodoTask);
                    }

                    foreach (var item in items)
                    {
                        writer.WriteLine(item.Description);
                    }

                    /* writer.WriteLine(DateTime.Now);   // write last saved
                     * writer.Write(content);            // write content */
                    content = writer.ToString();      // assign assembled content

                    writer.Dispose();                 // release writer
                }
                else if (dialog.FilterIndex == 2)
                {
                    System.IO.StringWriter       writer = new System.IO.StringWriter();
                    System.Collections.ArrayList list   = new System.Collections.ArrayList();
                    ItemCollection items = this.TodoTaskListView.Items;
                    foreach (var item in this.TodoTaskListView.Items)
                    {
                        items.Add(item as TodoTask);
                    }



                    // write as JSON
                    // create object to serialize


                    foreach (var item in items)
                    {
                        TodoTask todoTask = item as TodoTask;
                        list.Add(todoTask);
                    }
                    Models.TodoTask document = new Models.TodoTask(content);
                    // serialize type (Models.Document) to JSON string
                    string json = Newtonsoft
                                  .Json
                                  .JsonConvert
                                  .SerializeObject(document);
                    // set content to JSON result
                    content = json;                   // assign JSON string to content
                }

                else if (dialog.FilterIndex == 3)
                {
                    // write as XML
                    // create object to serialize
                    List <TodoTask> list  = new List <TodoTask>();
                    ItemCollection  items = this.TodoTaskListView.Items;

                    foreach (var item in items)
                    {
                        TodoTask todoTask = item as TodoTask;
                        list.Add(todoTask);
                    }

                    // create serializer
                    System.Xml.Serialization.XmlSerializer serializer =
                        new System.Xml.Serialization.XmlSerializer(typeof(List <ToDoApp.Wpf.Models.TodoTask>));
                    // this serializer writes to a stream
                    System.IO.MemoryStream stream = new System.IO.MemoryStream();
                    serializer.Serialize(stream, list);
                    stream.Seek(0, System.IO.SeekOrigin.Begin);   // reset stream to start

                    // read content from stream
                    System.IO.StreamReader reader = new System.IO.StreamReader(stream);
                    content = reader.ReadToEnd(); // assign XML string to content

                    reader.Dispose();             // dispose the reader
                    stream.Dispose();             // dispose the stream
                }
                else if (dialog.FilterIndex == 4)
                {
                    // write as SOAP
                    // note: have to add a reference to a global assembly (dll) to use in project
                    //create object to serialize

                    // todo
                    System.Collections.ArrayList list = new System.Collections.ArrayList();
                    ItemCollection items = this.TodoTaskListView.Items;

                    foreach (var item in items)
                    {
                        TodoTask todoTask = item as TodoTask;
                        list.Add(todoTask);
                    }



                    // create serializer
                    System.Runtime.Serialization.Formatters.Soap.SoapFormatter serializer =
                        new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();
                    // this serializer writes to a stream
                    System.IO.MemoryStream stream = new System.IO.MemoryStream();
                    serializer.Serialize(stream, list);
                    stream.Seek(0, System.IO.SeekOrigin.Begin);   // reset stream to start

                    // read content from stream
                    System.IO.StreamReader reader = new System.IO.StreamReader(stream);
                    content = reader.ReadToEnd(); // assign SOAP string to content

                    reader.Dispose();             // dispose the reader
                    stream.Dispose();             // dispose the stream
                }
                else // implies this is last one (binary)
                {
                    System.IO.StringWriter writer = new System.IO.StringWriter();
                    List <TodoTask>        items  = new List <TodoTask>();
                    foreach (var item in this.TodoTaskListView.Items)
                    {
                        items.Add(item as TodoTask);
                    }

                    foreach (var item in items)
                    {
                        writer.WriteLine(item.Description);
                    }

                    // write as binary
                    // create object to serialize
                    Models.TodoTask document = new Models.TodoTask(content);
                    // create serializer
                    System.Runtime.Serialization.Formatters.Binary.BinaryFormatter serializer =
                        new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                    // this serializer writes to a stream
                    System.IO.MemoryStream stream = new System.IO.MemoryStream();
                    serializer.Serialize(stream, document);

                    stream.Seek(0, System.IO.SeekOrigin.Begin);         // reset stream to start
                    // reading and writing binary data directly as string has issues, try not to do it
                    content = Convert.ToBase64String(stream.ToArray()); // assign base64 to content

                    stream.Dispose();                                   // dispose the stream
                }

                // write content to file
                System.IO.File.WriteAllText(filePath, content);

                /* string path = "output.txt";
                 * if (System.IO.File.Exists(path))
                 * {
                 *   File.Delete(path); //deletes the old file, creating a new list
                 *
                 *   System.IO.FileStream fileStream = System.IO.File.Open(
                 *   path,
                 *   System.IO.FileMode.Append,
                 *   System.IO.FileAccess.Write,
                 *   System.IO.FileShare.None);
                 *   System.IO.StreamWriter writer = new System.IO.StreamWriter(fileStream);
                 *
                 *   foreach (var item in TodoTaskListView.Items)
                 *   {
                 *       TodoTask listitem = item as TodoTask;
                 *       writer.WriteLine(listitem.Description);
                 *   }
                 *
                 *   writer.Close();
                 *   fileStream.Close();
                 * }
                 * else
                 * {
                 *   System.IO.StreamWriter writer = new System.IO.StreamWriter(path);
                 *
                 *   foreach (var item in TodoTaskListView.Items)
                 *   {
                 *       TodoTask listitem = item as TodoTask;
                 *       writer.WriteLine(listitem.Description);
                 *       //
                 *   }
                 *
                 *   writer.Close();
                 * }*/
            }
        }
Exemplo n.º 34
0
        private void FileOpen_Click(object sender, RoutedEventArgs e)
        {
            //old code that worked with defaul file path
            //string path = "output.txt";

            Microsoft.Win32.OpenFileDialog dialog = new Microsoft.Win32.OpenFileDialog();

            dialog.Filter = FilterTxt + "|" +
                            FilterJson + "|" +
                            FilterXml + "|" +
                            FilterSoap + "|" +
                            FilterBinary;

            dialog.FilterIndex = 1;
            bool?dialogResult = dialog.ShowDialog();

            if (dialogResult == true)
            {
                string filePath = dialog.FileName;

                if (System.IO.File.Exists(filePath))
                {
                    string content = string.Empty;

                    if (dialog.FilterIndex == 1)
                    {
                        System.IO.StringWriter writer = new System.IO.StringWriter();

                        ItemCollection items = this.TodoTaskListView.Items;
                        foreach (var item in items)
                        {
                            TodoTask todoTask = item as TodoTask;

                            writer.Write(todoTask.LastSaved);
                            writer.Write(todoTask.IsComplete);
                            writer.Write(todoTask.Description);
                        }
                        content = writer.ToString();
                        writer.Dispose();
                    }


                    else if (dialog.FilterIndex == 2)
                    {
                        // read as JSON
                        string json = content;
                        // deserialize to expected type (Models.Document)
                        object jsonObject = Newtonsoft.Json
                                            .JsonConvert
                                            .DeserializeObject(json, typeof(Models.TodoTask));
                        // cast and assign JSON object to expected type (Models.Document)
                        Models.TodoTask items = (Models.TodoTask)jsonObject;
                        // assign content from deserialized Models.Document
                        content = items.Content;
                    }


                    else if (dialog.FilterIndex == 3)
                    {
                        // read as XML for type of Models.Document
                        System.Xml.Serialization.XmlSerializer serializer =
                            new System.Xml.Serialization.XmlSerializer(typeof(Models.TodoTask));

                        // convert content to byte array (sequence of bytes)
                        byte[] buffer = System.Text.Encoding.ASCII.GetBytes(content);
                        // make stream from buffer
                        System.IO.MemoryStream stream = new System.IO.MemoryStream(buffer);
                        // deserialize stream to an object
#pragma warning disable CA5369 // Use XmlReader For Deserialize
                        object xmlObject = serializer.Deserialize(stream);
#pragma warning restore CA5369 // Use XmlReader For Deserialize
                               // cast and assign XML object to actual type object
                        Models.TodoTask items = (Models.TodoTask)xmlObject;

                        content = items.Content;
                        stream.Dispose();   // release the resources
                    }


                    else if (dialog.FilterIndex == 4)
                    {
                        // read as soap
                        System.Runtime.Serialization.Formatters.Soap.SoapFormatter serializer =
                            new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();

                        // convert content to byte array (sequence of bytes)
                        byte[] buffer = System.Text.Encoding.ASCII.GetBytes(content);
                        // make stream from buffer
                        System.IO.MemoryStream stream = new System.IO.MemoryStream(buffer);
                        // deserialize stream to an object
                        object soapObject = serializer.Deserialize(stream);
                        // cast and assign SOAP object to actual type object
                        Models.TodoTask document = (Models.TodoTask)soapObject;
                        // read content
                        content = document.Content;

                        stream.Dispose();   // release the resources
                    }


                    else if (dialog.FilterIndex == 5)
                    {
                        // read as binary
                        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter serializer =
                            new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

                        // reading and writing binary data directly as string has issues, try not to do it
                        byte[] buffer = Convert.FromBase64String(content);
                        System.IO.MemoryStream stream = new System.IO.MemoryStream(buffer);
                        // deserialize stream to object
                        object binaryObject = serializer.Deserialize(stream);
                        // assign binary object to actual type object
                        Models.TodoTask items = (Models.TodoTask)binaryObject;
                        // read the content
                        content = items.Content;
                        stream.Dispose();   // release the resources
                    }
                    else // imply this is any file
                    {
                        // read as is
                    }

                    // assign content to UI control
                    // ~~~~~~~ UserText.Text = content; ~~~~~~~~~~~~~~~~~~~

                    //old code that worked with defaul file path

                    /*if (System.IO.File.Exists(path))
                     * {
                     *  System.IO.FileStream fileStream = System.IO.File.Open(
                     *  path,
                     *  System.IO.FileMode.Open,
                     *  System.IO.FileAccess.Read,
                     *  System.IO.FileShare.None);
                     *  System.IO.StreamReader reader = new System.IO.StreamReader(fileStream);
                     *  while (reader.EndOfStream == false)
                     *  {
                     *      string line = reader.ReadLine();
                     *      TodoTask item = new TodoTask();
                     *      item.Description = line;
                     *      TodoTaskListView.Items.Add(item);
                     *  }
                     *  reader.Close();
                     *  fileStream.Close();
                     * }*/

                    //below is part of the save file code

                    /*System.IO.StringWriter writer = new System.IO.StringWriter();
                     * List<TodoTask> items = new List<TodoTask>();
                     * foreach (var item in this.TodoTaskListView.Items)
                     * {
                     *  items.Add(item as TodoTask);
                     * }
                     *
                     * foreach (var item in items)
                     * {
                     *  writer.WriteLine(item.Description);
                     * }*/
                }
            }
        }
Exemplo n.º 35
0
        public void Xml()
        {
            var serializer = new System.Xml.Serialization.XmlSerializer(typeof(object));

            serializer.Deserialize(new MemoryStream());
        }
        public static XmlSyndicationContent CreateXmlContent(Object xmlSerializerObject, System.Xml.Serialization.XmlSerializer serializer)
        {
            Contract.Ensures(Contract.Result <System.ServiceModel.Syndication.XmlSyndicationContent>() != null);

            return(default(XmlSyndicationContent));
        }
Exemplo n.º 37
0
        private void PerformActMainframeGetDetails(Act act)
        {
            ActMainframeGetDetails MFGD = (ActMainframeGetDetails)act;

            //todo Implement get Type and others


            switch (MFGD.DetailsToFetch)
            {
            case ActMainframeGetDetails.eDetailsToFetch.GetText:

                ActMainFrameGetText(act);

                break;

            case ActMainframeGetDetails.eDetailsToFetch.GetDetailsFromText:

                MainframeGetDetailsFromText(act);
                break;

            case ActMainframeGetDetails.eDetailsToFetch.GetAllEditableFeilds:

                XmlDocument    XD  = new XmlDocument();
                XmlDeclaration dec = XD.CreateXmlDeclaration("1.0", null, null);
                XD.AppendChild(dec);
                XmlElement root = XD.CreateElement("EditableFields");
                XD.AppendChild(root);

                string CaretValuePair = @"<?xml version='1.0' encoding='UTF-8'?><nodes>";

                XMLScreen XC = MFE.GetScreenAsXML();
                foreach (XMLScreenField XSF in XC.Fields)
                {
                    if (XSF.Attributes.Protected)
                    {
                        continue;
                    }
                    string node = "<node caret=\"" + XSF.Location.position.ToString() + "\" text=\"" + XSF.Text + "\"> </node>";

                    CaretValuePair = CaretValuePair + node;

                    XmlElement EditableField = XD.CreateElement("EditableField");
                    EditableField.SetAttribute("Caret", XSF.Location.position.ToString());
                    EditableField.SetAttribute("Text", XSF.Text);
                    root.AppendChild(EditableField);
                }

                act.AddOrUpdateReturnParamActual("Fields", XD.OuterXml);

                break;

            case ActMainframeGetDetails.eDetailsToFetch.GetCurrentScreenAsXML:

                Open3270.TN3270.XMLScreen XMLS = MFE.GetScreenAsXML();
                System.Xml.Serialization.XmlSerializer xsSubmit = new System.Xml.Serialization.XmlSerializer(typeof(Open3270.TN3270.XMLScreen));
                System.IO.StringWriter sww    = new System.IO.StringWriter();
                System.Xml.XmlWriter   writer = System.Xml.XmlWriter.Create(sww);

                xsSubmit.Serialize(writer, XMLS);
                String ScreenXML = sww.ToString();     // Your XML

                act.AddOrUpdateReturnParamActual("ScreenXML", ScreenXML);

                break;

            default:
                throw new NotSupportedException("The action is not supporte yet");
            }
        }
Exemplo n.º 38
0
        private async void Save_B_Click(object sender, RoutedEventArgs e)
        {
            if (IsModelCreating)
            {
                MessageBox.Show("処理が実行中です。");
                return;
            }
            if (Map_Scale_T.Text == "")
            {
                MessageBox.Show("マップサイズの欄が空白です。");
                return;
            }
            else if (Map_Scale_T.Text == "0")
            {
                MessageBox.Show("マップサイズを0にすることはできません。");
                return;
            }
            try
            {
                Map_X = int.Parse(Map_Position_X.Text);
                Map_Y = int.Parse(Map_Position_Y.Text);
                Map_Z = int.Parse(Map_Position_Z.Text);
            }
            catch
            {
                MessageBox.Show("位置が正しくありません。");
                return;
            }
            try
            {
                Map_Scale = int.Parse(Map_Scale_T.Text);
            }
            catch
            {
                MessageBox.Show("マップサイズが正しくありません。");
                return;
            }
            try
            {
                Map_Rotate = int.Parse(Map_Rotate_T.Text);
            }
            catch
            {
                MessageBox.Show("横回転の項目に誤りがあります。");
                return;
            }
            IsModelCreating   = true;
            Menu.Visibility   = Visibility.Visible;
            Wait_P.Visibility = Visibility.Visible;
            Wait_T.Visibility = Visibility.Visible;
            while (Wait_T.Opacity < 1)
            {
                Wait_P.Opacity += 0.05;
                Wait_T.Opacity += 0.05;
                await Task.Delay(1000 / 60);
            }
            bool Wait    = true;
            Task task_01 = Task.Run(() =>
            {
                Task task_02 = Task.Run(() =>
                {
                    int ModelHandle = DX.MV1LoadModel(FilePath);
                    DX.MV1SaveModelToMV1File(ModelHandle, Path + "/Resources/Map/UserMap/Model.mv1", DX.MV1_SAVETYPE_NORMAL, 0, DX.FALSE, 0, 0, 0, 0);
                    DX.MV1DeleteModel(ModelHandle);
                });
                task_02.Wait();
                Wait = false;
            });

            while (Wait)
            {
                await Task.Delay(1000);
            }
            Wait_T.Text = "処理が完了しました。";
            await Task.Delay(500);

            while (Wait_T.Opacity > 0)
            {
                Wait_P.Opacity -= 0.05;
                Wait_T.Opacity -= 0.05;
                await Task.Delay(1000 / 60);
            }
            Wait_P.Visibility = Visibility.Hidden;
            Wait_T.Visibility = Visibility.Hidden;
            Menu.Visibility   = Visibility.Hidden;
            IsModelCreating   = false;
            StreamWriter s = File.CreateText(Path + "/Resources/Map_Setting.dat");

            s.Close();
            Map_Setting obj = new Map_Setting
            {
                Map_Scale  = Map_Scale,
                Map_X      = Map_X,
                Map_Y      = Map_Y,
                Map_Z      = Map_Z,
                Map_Rotate = Map_Rotate,
                Sky_Enable = Sky_Enable,
                Name       = Name
            };

            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(Map_Setting));
            StreamWriter sw = new StreamWriter(Path + "/Resources/Map_Setting.dat", false, new System.Text.UTF8Encoding(false));

            serializer.Serialize(sw, obj);
            sw.Close();
            XDocument item    = XDocument.Load(Path + "/Resources/Setting.dat");
            XElement  item_01 = item.Element("Setting_Save");
            string    Temp    = "";
            string    Replace = "";

            if (item_01.Element("Map_Select").Value == "0")
            {
                Temp    = "町";
                Replace = "<Map_Select>0</Map_Select>";
            }
            else if (item_01.Element("Map_Select").Value == "1")
            {
                Temp    = "宇宙";
                Replace = "<Map_Select>1</Map_Select>";
            }
            else
            {
                return;
            }
            MessageBoxResult result = MessageBox.Show("現在指定されているマップは" + Temp + "です。ユーザーマップに変更しますか?", "確認", MessageBoxButton.YesNo, MessageBoxImage.Exclamation, MessageBoxResult.Yes);

            if (result == MessageBoxResult.Yes)
            {
                StreamReader str  = new StreamReader(Path + "/Resources/Setting.dat");
                string       Read = str.ReadToEnd();
                str.Close();
                File.Delete(Path + "/Resources/Setting.dat");
                StreamWriter stw = File.CreateText(Path + "/Resources/Setting.dat");
                stw.Write(Read.Replace(Replace, "<Map_Select>2</Map_Select>"));
                stw.Close();
            }
        }
Exemplo n.º 39
0
        /// <summary>
        /// Run the BCC models
        /// </summary>
        /// <param name="modelName"></param>
        /// <param name="data"></param>
        /// <param name="fullData"></param>
        /// <param name="model"></param>
        /// <param name="mode"></param>
        /// <param name="calculateAccuracy"></param>
        /// <param name="numCommunities"></param>
        /// <param name="serialize"></param>
        /// <param name="serializeCommunityPosteriors"></param>
        public void RunBCC(string modelName,
                           IList <Datum> data,
                           IList <Datum> fullData,
                           BCC model,
                           RunMode mode,
                           bool calculateAccuracy,
                           int numCommunities = -1,
                           bool serialize     = false,
                           bool serializeCommunityPosteriors = false)
        {
            CBCC communityModel = model as CBCC;

            IsCommunityModel = communityModel != null;


            bool IsBCC = !(IsCommunityModel);

            if (this.Mapping == null)
            {
                this.Mapping     = new DataMapping(fullData, numCommunities);
                this.FullMapping = Mapping;
                this.GoldLabels  = this.Mapping.GetGoldLabelsPerTaskId();
            }

            bool createModel = (Mapping.LabelCount != model.LabelCount) || (Mapping.TaskCount != model.TaskCount);

            if (IsCommunityModel)
            {
                //Console.WriteLine("--- CBCC ---");
                CommunityCount = numCommunities;
                createModel    = createModel || (numCommunities != communityModel.CommunityCount);

                if (createModel)
                {
                    communityModel.CreateModel(Mapping.TaskCount, Mapping.LabelCount, numCommunities);
                }
            }
            else if (createModel)
            {
                model.CreateModel(Mapping.TaskCount, Mapping.LabelCount);
            }

            BCCPosteriors priors = null;

            switch (mode)
            {
            case RunMode.Prediction:
                priors = ToPriors();
                break;

            default:
                ClearResults();

                if (mode == RunMode.LoadAndUseCommunityPriors && IsCommunityModel)
                {
                    priors = DeserializeCommunityPosteriors(modelName, numCommunities);
                }
                break;
            }

            // Get data structures
            int[][] taskIndices  = Mapping.GetTaskIndicesPerWorkerIndex(data);
            int[][] workerLabels = Mapping.GetLabelsPerWorkerIndex(data);

            if (mode == RunMode.Prediction)
            {
                // Signal prediction mode by setting all labels to null
                workerLabels = workerLabels.Select(arr => (int[])null).ToArray();
            }

            // Call inference
            BCCPosteriors posteriors = model.Infer(
                taskIndices,
                workerLabels,
                priors);

            UpdateResults(posteriors, mode);

            if (calculateAccuracy)
            {
                UpdateAccuracy();
            }

            if (serialize)
            {
                using (FileStream stream = new FileStream(modelName + ".xml", FileMode.Create))
                {
                    var serializer = new System.Xml.Serialization.XmlSerializer(IsCommunityModel ? typeof(CBCCPosteriors) : typeof(BCCPosteriors));
                    serializer.Serialize(stream, posteriors);
                }
            }

            if (serializeCommunityPosteriors && IsCommunityModel)
            {
                SerializeCommunityPosteriors(modelName);
            }
        }
Exemplo n.º 40
0
 public XmlSerializer(string fileName = null)
 {
     _formatter = new System.Xml.Serialization.XmlSerializer(typeof(T));
     _fileName  = fileName;
 }
Exemplo n.º 41
0
 public static TaskQueueData DeserializeFromXml(string sXml)
 {
     System.IO.StringReader sr = new System.IO.StringReader(sXml);
     System.Xml.Serialization.XmlSerializer formatter = new System.Xml.Serialization.XmlSerializer(typeof(TaskQueueData));
     return(formatter.Deserialize(sr) as TaskQueueData);
 }
Exemplo n.º 42
0
        static void Main(string[] args)
        {
            //ConfigurationConvertor.Convert(
            //    @"E:\assetasyst.xml",
            //    @"E:\assetasyst.proj.xml");

            var     assembler  = new ProjectAssembler(new ConfigurationAssembler(new SubjectAssembler(new FieldAssembler(new ParserAssembler()))));
            var     serializer = new System.Xml.Serialization.XmlSerializer(typeof(ProjectDTO));
            Project p;


            //var dto = assembler.Create(new Project() { Configuration = new dbqf.tests.Chinook() });
            //var list = new List<dbqf.Serialization.DTO.Parsers.ParserDTO>();
            //list.Add(new dbqf.Serialization.DTO.Parsers.DelimitedParserDTO(new string[] { ",", ";", "<", Environment.NewLine, "\"", "\t" }));
            //list.Add(new dbqf.Serialization.DTO.Parsers.ConvertParserDTO() { FromType = typeof(object).FullName, ToType = typeof(string).FullName });
            //dto.Configuration.Subjects[0].Fields[0].Parsers = list;
            //File.Delete(@"E:\chinook.proj.xml");

            //var ws = new System.Xml.XmlWriterSettings();
            //ws.Indent = true;
            //ws.IndentChars = "  ";
            //ws.CheckCharacters = true;
            //using (XmlWriter writer = XmlWriter.Create(@"E:\chinook.proj.xml", ws))
            //    serializer.Serialize(writer, dto);

            //File.WriteAllText(@"E:\AssetAsystConfiguration.cs", new FluentGenerator().Generate(new dbqf.tests.Chinook(), "dbqf.tests", "Chinook"));



            //p = new Project()
            //{
            //    Id = Guid.NewGuid(),
            //    Configuration = Build(),
            //    Connections = new List<Connection>()
            //    {
            //        new Connection()
            //        {
            //            ConnectionType = "SqlClient",
            //            DisplayName = "Live",
            //            Identifier = "live",
            //            ConnectionString = "Server=LAU-SQL2005;Database=DownloadCentre;Trusted_Connection=True;" }
            //    }
            //};
            //var dto = assembler.Create(p);
            //dto.Configuration[0].Fields[1].Parsers.Add(new ParserDTO() { TypeName = typeof(DelimitedParser).Name, Delimiters = new string[] { "," } });
            //using (TextWriter writer = new StreamWriter(@"E:\Users\sattenborrow\Documents\Visual Studio 2010\Projects\db-query-framework\configurations\download-centre.proj.xml"))
            //    serializer.Serialize(writer, dto);


            var rs = new XmlReaderSettings();

            rs.CheckCharacters = true; // required to read special characters like new line and tab
            using (XmlReader reader = XmlReader.Create(@"E:\assetasyst.proj.xml", rs))
                p = assembler.Restore((ProjectDTO)serializer.Deserialize(reader));

            //var validator = new ConfigurationValidation(p.Configuration, new SqlConnection(p.Connections[0].ConnectionString));
            var validator = new ConfigurationValidation(new dbqf.AssetAsyst.AssetAsystConfiguration(), new SqlConnection(@"Server=(local)\sql2012;Database=AMS_Pittsh;Trusted_Connection=True;"));

            validator.Validate();

            //File.WriteAllText(@"E:\assetasyst.cs", new FluentGenerator().Generate(p.Configuration, "dbqf.AssetAsyst", "Configuration"));

            //var validator = new ConfigurationValidation(p.Configuration, new SqlConnection(p.Connections[0].ConnectionString));
            //validator.Validate(true);


            Console.WriteLine("\nDone.");
            Console.ReadKey();
        }
Exemplo n.º 43
0
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            Document doc = commandData.Application.ActiveUIDocument.Document;

            if (!doc.IsWorkshared)
            {
                message = "Файл не является файлом совместной работы";
                return(Result.Failed);;
            }

            //считываю список рабочих наборов
            string dllPath = System.Reflection.Assembly.GetExecutingAssembly().Location;
            string folder  = System.IO.Path.GetDirectoryName(dllPath);

            System.Windows.Forms.OpenFileDialog dialog = new System.Windows.Forms.OpenFileDialog();
            dialog.InitialDirectory = folder;
            dialog.Multiselect      = false;
            dialog.Filter           = "xml files (*.xml)|*.xml|All files (*.*)|*.*";
            if (dialog.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                return(Result.Cancelled);
            }
            string xmlFilePath = dialog.FileName;

            InfosStorage storage = new InfosStorage();

            System.Xml.Serialization.XmlSerializer serializer =
                new System.Xml.Serialization.XmlSerializer(typeof(InfosStorage));
            using (StreamReader r = new StreamReader(xmlFilePath))
            {
                storage = (InfosStorage)serializer.Deserialize(r);
            }
            if (storage.LinkedFilesPrefix == null)
            {
                storage.LinkedFilesPrefix = "#";
            }

            using (Transaction t = new Transaction(doc))
            {
                t.Start("Создание рабочих наборов");

                //назначаю рабочие наборы в случае, если указана категория
                foreach (WorksetByCategory wb in storage.worksetsByCategory)
                {
                    Workset wset = wb.GetWorkset(doc);
                    List <BuiltInCategory> cats = wb.revitCategories;
                    if (cats == null)
                    {
                        continue;
                    }
                    if (cats.Count == 0)
                    {
                        continue;
                    }

                    foreach (BuiltInCategory bic in cats)
                    {
                        List <Element> elems = new FilteredElementCollector(doc)
                                               .OfCategory(bic)
                                               .WhereElementIsNotElementType()
                                               .ToElements()
                                               .ToList();

                        foreach (Element elem in elems)
                        {
                            WorksetBy.SetWorkset(elem, wset);
                        }
                    }
                }

                //назначаю рабочие наборы по именам семейств
                List <FamilyInstance> famIns = new FilteredElementCollector(doc)
                                               .WhereElementIsNotElementType()
                                               .OfClass(typeof(FamilyInstance))
                                               .Cast <FamilyInstance>()
                                               .ToList();
                foreach (WorksetByFamily wb in storage.worksetsByFamily)
                {
                    Workset wset = wb.GetWorkset(doc);

                    List <string> families = wb.FamilyNames;
                    if (families == null)
                    {
                        continue;
                    }
                    if (families.Count == 0)
                    {
                        continue;
                    }



                    foreach (string familyName in families)
                    {
                        List <FamilyInstance> curFamIns = famIns
                                                          .Where(f => f.Symbol.FamilyName.StartsWith(familyName))
                                                          .ToList();

                        foreach (FamilyInstance fi in curFamIns)
                        {
                            WorksetBy.SetWorkset(fi, wset);
                        }
                    }
                }

                //назначаю рабочие наборы по именам типов
                List <Element> allElems = new FilteredElementCollector(doc)
                                          .WhereElementIsNotElementType()
                                          .Cast <Element>()
                                          .ToList();

                foreach (WorksetByType wb in storage.worksetsByType)
                {
                    Workset       wset      = wb.GetWorkset(doc);
                    List <string> typeNames = wb.TypeNames;
                    if (typeNames == null)
                    {
                        continue;
                    }
                    if (typeNames.Count == 0)
                    {
                        continue;
                    }

                    foreach (string typeName in typeNames)
                    {
                        foreach (Element elem in allElems)
                        {
                            ElementId typeId = elem.GetTypeId();
                            if (typeId == null || typeId == ElementId.InvalidElementId)
                            {
                                continue;
                            }
                            ElementType elemType = doc.GetElement(typeId) as ElementType;
                            if (elemType == null)
                            {
                                continue;
                            }

                            if (elemType.Name.StartsWith(typeName))
                            {
                                WorksetBy.SetWorkset(elem, wset);
                            }
                        }
                    }
                }

                //назначаю рабочие наборы по значению параметров
                foreach (WorksetByParameter wb in storage.worksetsByParameter)
                {
                    Workset wset       = wb.GetWorkset(doc);
                    string  paramName  = wb.ParameterName;
                    string  paramValue = wb.ParameterValue;

                    List <Element> elemsFilterByParam = allElems
                                                        .Where(e => e.LookupParameter(paramName).AsString().Equals(paramValue)).ToList();

                    foreach (Element elem in elemsFilterByParam)
                    {
                        WorksetBy.SetWorkset(elem, wset);
                    }
                }


                //назначаю рабочие наборы для связанных файлов
                List <RevitLinkInstance> links = new FilteredElementCollector(doc)
                                                 .OfClass(typeof(RevitLinkInstance))
                                                 .Cast <RevitLinkInstance>()
                                                 .ToList();

                foreach (RevitLinkInstance rli in links)
                {
                    RevitLinkType linkFileType = doc.GetElement(rli.GetTypeId()) as RevitLinkType;
                    if (linkFileType == null)
                    {
                        continue;
                    }
                    if (linkFileType.IsNestedLink)
                    {
                        continue;
                    }

                    string linkWorksetName1 = rli.Name.Split(':')[0];
                    string linkWorksetName2 = linkWorksetName1.Substring(0, linkWorksetName1.Length - 5);
                    string linkWorksetName  = storage.LinkedFilesPrefix + linkWorksetName2;
                    bool   checkExists      = WorksetTable.IsWorksetNameUnique(doc, linkWorksetName);
                    if (!checkExists)
                    {
                        continue;
                    }

                    Workset.Create(doc, linkWorksetName);

                    Workset linkWorkset = new FilteredWorksetCollector(doc)
                                          .OfKind(WorksetKind.UserWorkset)
                                          .ToWorksets()
                                          .Where(w => w.Name == linkWorksetName)
                                          .First();

                    WorksetBy.SetWorkset(rli, linkWorkset);
                    WorksetBy.SetWorkset(linkFileType, linkWorkset);
                }

                t.Commit();
            }

            List <string> emptyWorksetsNames = WorksetTool.GetEmptyWorksets(doc);

            if (emptyWorksetsNames.Count > 0)
            {
                string msg = "Обнаружены пустые рабочие наборы! Их можно удалить вручную:\n";
                foreach (string s in emptyWorksetsNames)
                {
                    msg += s + "\n";
                }
                TaskDialog.Show("Отчёт", msg);
            }

            return(Result.Succeeded);
        }
Exemplo n.º 44
0
        static protected void LoadSettings()
        {
            Type T = Settings.GetType();

            System.Xml.Serialization.XmlSerializer serializer = new
                                                                System.Xml.Serialization.XmlSerializer(T);

            System.IO.FileStream fs = null;


            // A FileStream is needed to read the XML document.
            try
            {
                fs = new System.IO.FileStream(filename, System.IO.FileMode.Open);
            }
            catch (System.IO.FileNotFoundException fex)
            {
                //file not found. create file by saving current(probably defaults) and then load it
                SaveSettings();
                fs = new System.IO.FileStream(filename, System.IO.FileMode.Open);
            }
            catch (Exception e)
            {
                return;
            }
            if (fs != null)
            {
                try
                {
                    XmlReader reader = XmlReader.Create(fs);

                    // Use the Deserialize method to restore the object's state.
                    lock (padlock)
                    {
                        loadingSettings = true;
                        try
                        {
                            var loadedSettings = serializer.Deserialize(reader);
                            if (loadedSettings.GetType() == Settings.GetType())
                            {
                                Settings = Cast(loadedSettings, T);
                            }
                            else
                            {
                                throw new ArgumentException("Settings wrong type!");
                            }
                        }
                        catch (Exception e)
                        {
                            loadingSettings = false;
                            //error loading settings. we'll have to remake the file with the default settings :)
                            fs.Close();
                            System.IO.File.Delete(filename);
                            SaveSettings();
                        }
                    }

                    fs.Close();
                }
                catch (Exception e)
                {
                    fs.Close();
                }
            }
            loadingSettings = false;
            return;
        }
Exemplo n.º 45
0
        public static void PopulateFromFile(string filename, ref Options o)
        {
            using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read)) {
                if (filename.EndsWith(".xml", StringComparison.InvariantCultureIgnoreCase))
                {
                    var writer = new System.Xml.Serialization.XmlSerializer(typeof(Options));
                    o = (Options)writer.Deserialize(fs);
                }
                else
                {
                    using (StreamReader sr = new StreamReader(fs)) {
                        string line;
                        bool   active = false;
                        while ((line = sr.ReadLine()) != null)
                        {
                            if (line.StartsWith(";"))
                            {
                                continue;
                            }
                            if (line.StartsWith("["))
                            {
                                active = line.Equals("[LoopingAudioConverter]", StringComparison.InvariantCultureIgnoreCase);
                                continue;
                            }

                            string[] split = line.Split('=');
                            if (split.Length == 2)
                            {
                                string v = split[1];
                                switch (split[0])
                                {
                                case "OutputDir":
                                    o.OutputDir = v;
                                    break;

                                case "MaxChannels":
                                    o.MaxChannels = int.Parse(v);
                                    break;

                                case "MaxSampleRate":
                                    o.MaxSampleRate = int.Parse(v);
                                    break;

                                case "AmplifydB":
                                    o.AmplifydB = decimal.Parse(v);
                                    break;

                                case "AmplifyRatio":
                                    o.AmplifyRatio = decimal.Parse(v);
                                    break;

                                case "ChannelSplit":
                                    o.ChannelSplit = (ChannelSplit)Enum.Parse(typeof(ChannelSplit), v, true);
                                    break;

                                case "ExporterType":
                                    o.ExporterType = (ExporterType)Enum.Parse(typeof(ExporterType), v, true);
                                    break;

                                case "MP3EncodingParameters":
                                    o.MP3EncodingParameters = v;
                                    break;

                                case "OggVorbisEncodingParameters":
                                    o.OggVorbisEncodingParameters = v;
                                    break;

                                case nameof(o.AACEncodingParameters):
                                    o.AACEncodingParameters = v;
                                    break;

                                case "BxstmCodec":
                                    o.BxstmOptions.Codec = v == "Adpcm"
                                                                                        ? NwCodec.GcAdpcm
                                                                                        : (NwCodec)Enum.Parse(typeof(NwCodec), v, true);
                                    break;

                                case "ExportWholeSong":
                                    o.ExportWholeSong = bool.Parse(v);
                                    break;

                                case "WholeSongSuffix":
                                    o.WholeSongSuffix = v;
                                    break;

                                case "NumberOfLoops":
                                    o.NumberOfLoops = int.Parse(v);
                                    break;

                                case "FadeOutSec":
                                    o.FadeOutSec = decimal.Parse(v);
                                    break;

                                case "WriteLoopingMetadata":
                                    o.WriteLoopingMetadata = bool.Parse(v);
                                    break;

                                case "ExportPreLoop":
                                    o.ExportPreLoop = bool.Parse(v);
                                    break;

                                case "PreLoopSuffix":
                                    o.PreLoopSuffix = v;
                                    break;

                                case "ExportLoop":
                                    o.ExportLoop = bool.Parse(v);
                                    break;

                                case "LoopSuffix":
                                    o.LoopSuffix = v;
                                    break;

                                case "ShortCircuit":
                                    o.ShortCircuit = bool.Parse(v);
                                    break;

                                case "VGAudioDecoder":
                                    o.VGAudioDecoder = bool.Parse(v);
                                    break;

                                case "NumSimulTasks":
                                    o.NumSimulTasks = int.Parse(v);
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 46
0
 public static void WriteToFile(string filename, Options o)
 {
     using (FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write)) {
         if (filename.EndsWith(".xml", StringComparison.InvariantCultureIgnoreCase))
         {
             var writer = new System.Xml.Serialization.XmlSerializer(typeof(Options));
             writer.Serialize(fs, o);
         }
         else
         {
             using (StreamWriter sw = new StreamWriter(fs)) {
                 sw.WriteLine("[LoopingAudioConverter]");
                 if (o.OutputDir != null)
                 {
                     sw.WriteLine("OutputDir=" + o.OutputDir);
                 }
                 if (o.MaxChannels != null)
                 {
                     sw.WriteLine("MaxChannels=" + o.MaxChannels);
                 }
                 if (o.MaxSampleRate != null)
                 {
                     sw.WriteLine("MaxSampleRate=" + o.MaxSampleRate);
                 }
                 if (o.AmplifydB != null)
                 {
                     sw.WriteLine("AmplifydB=" + o.AmplifydB);
                 }
                 if (o.AmplifyRatio != null)
                 {
                     sw.WriteLine("AmplifyRatio=" + o.AmplifyRatio);
                 }
                 if (o.ChannelSplit != null)
                 {
                     sw.WriteLine("ChannelSplit=" + o.ChannelSplit);
                 }
                 if (o.ExporterType != null)
                 {
                     sw.WriteLine("ExporterType=" + o.ExporterType);
                 }
                 if (o.MP3EncodingParameters != null)
                 {
                     sw.WriteLine("MP3EncodingParameters=" + o.MP3EncodingParameters);
                 }
                 if (o.OggVorbisEncodingParameters != null)
                 {
                     sw.WriteLine("OggVorbisEncodingParameters=" + o.OggVorbisEncodingParameters);
                 }
                 if (o.AACEncodingParameters != null)
                 {
                     sw.WriteLine(nameof(o.AACEncodingParameters) + "=" + o.AACEncodingParameters);
                 }
                 if (o.BxstmOptions.Codec != null)
                 {
                     sw.WriteLine("BxstmCodec=" + o.BxstmOptions.Codec);
                 }
                 if (o.ExportWholeSong != null)
                 {
                     sw.WriteLine("ExportWholeSong=" + o.ExportWholeSong);
                 }
                 if (o.WholeSongSuffix != null)
                 {
                     sw.WriteLine("WholeSongSuffix=" + o.WholeSongSuffix);
                 }
                 if (o.NumberOfLoops != null)
                 {
                     sw.WriteLine("NumberOfLoops=" + o.NumberOfLoops);
                 }
                 if (o.FadeOutSec != null)
                 {
                     sw.WriteLine("FadeOutSec=" + o.FadeOutSec);
                 }
                 if (o.WriteLoopingMetadata != null)
                 {
                     sw.WriteLine("WriteLoopingMetadata=" + o.WriteLoopingMetadata);
                 }
                 if (o.ExportPreLoop != null)
                 {
                     sw.WriteLine("ExportPreLoop=" + o.ExportPreLoop);
                 }
                 if (o.PreLoopSuffix != null)
                 {
                     sw.WriteLine("PreLoopSuffix=" + o.PreLoopSuffix);
                 }
                 if (o.ExportLoop != null)
                 {
                     sw.WriteLine("ExportLoop=" + o.ExportLoop);
                 }
                 if (o.LoopSuffix != null)
                 {
                     sw.WriteLine("LoopSuffix=" + o.LoopSuffix);
                 }
                 if (o.ShortCircuit != null)
                 {
                     sw.WriteLine("ShortCircuit=" + o.ShortCircuit);
                 }
                 if (o.VGAudioDecoder != null)
                 {
                     sw.WriteLine("VGAudioDecoder=" + o.ShortCircuit);
                 }
                 if (o.NumSimulTasks != null)
                 {
                     sw.WriteLine("NumSimulTasks=" + o.NumSimulTasks);
                 }
             }
         }
     }
 }
Exemplo n.º 47
0
        protected override TEntity Deserialize(FileStream fileStream)
        {
            var xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(TEntity));

            return((TEntity)xmlSerializer.Deserialize(fileStream));
        }
Exemplo n.º 48
0
        }         // public void initRelations()

        private Layer createLayer(string id, bool vis)
        {
            // create Layer according to its Type
            string typ = lyrType;

            ESRI.ArcGIS.Client.Layer res = new ESRI.ArcGIS.Client.GraphicsLayer();

            if (typ == "ArcGISTiledMapServiceLayer")
            {
                var lr = new ESRI.ArcGIS.Client.ArcGISTiledMapServiceLayer();
                lr.Url      = lyrUrl;
                lr.ProxyURL = proxy;
                res         = lr;
            }
            else if (typ == "OpenStreetMapLayer")
            {
                var lr = new ESRI.ArcGIS.Client.Toolkit.DataSources.OpenStreetMapLayer();
                res = lr;
            }
            else if (typ == "ArcGISDynamicMapServiceLayer")
            {
                var lr = new ESRI.ArcGIS.Client.ArcGISDynamicMapServiceLayer();
                lr.Url         = lyrUrl;
                lr.ProxyURL    = proxy;
                lr.ImageFormat = imageFormat;
                res            = lr;
            }
            else if (typ == "FeatureLayer")
            {
                var lr = new ESRI.ArcGIS.Client.FeatureLayer()
                {
                    Url = lyrUrl, ProxyUrl = proxy
                };
                lr.OutFields.Add("*");
                lr.Mode = FeatureLayer.QueryMode.OnDemand;
                lr.Initialize();                 // retrieve attribs from server
                var rr = rendererFromJson(renderer);
                if (rr != null)
                {
                    lr.Renderer = rr;
                }
                res = lr;
            }
            else if (typ == "GraphicsLayer")
            {
                var gl = setContent(id, lyrUrl);
                var rr = rendererFromJson(renderer);
                if (rr != null)
                {
                    gl.Renderer = rr;
                }
                res = gl;
            }

            if (res != null)
            {
                ESRI.ArcGIS.Client.Extensibility.LayerProperties.SetIsPopupEnabled(res, popupOn);

                // sublayers popups on/off
                if (identifyLayerIds.Length <= 3)
                {
                    ;
                }
                else
                {
                    var xmlszn = new System.Xml.Serialization.XmlSerializer(typeof(System.Collections.ObjectModel.Collection <int>));
                    var sr     = new StringReader(identifyLayerIds);
                    var ids    = xmlszn.Deserialize(sr) as System.Collections.ObjectModel.Collection <int>;
                    ESRI.ArcGIS.Mapping.Core.LayerExtensions.SetIdentifyLayerIds(res, ids);
                }
            }

            return(res);
        }         // private Layer createLayer(string id, bool vis)
Exemplo n.º 49
0
        public override void RunAction(Act act)
        {
            if (act.GetType().ToString() == "GingerCore.Actions.ActScreenShot")
            {
                TakeScreenShot(act);
                return;
            }

            try
            {
                switch (act.GetType().ToString())
                {
                case "GingerCore.Actions.MainFrame.ActMainframeGetDetails":

                    ActMainframeGetDetails MFGD = (ActMainframeGetDetails)act;
                    //todo Implement get Type and others

                    int locx = -1;
                    int locy = -1;
                    switch (MFGD.DetailsToFetch)
                    {
                    case ActMainframeGetDetails.eDetailsToFetch.GetText:

                        if (MFGD.LocateBy == eLocateBy.ByCaretPosition)
                        {
                            if (String.IsNullOrEmpty(act.ValueForDriver))
                            {
                                string MFText = MFE.GetTextatPosition(Int32.Parse(MFGD.LocateValueCalculated), 50);
                                MFText = MFText.Split().ElementAt(0).ToString();
                                MFGD.AddOrUpdateReturnParamActual("Value", MFText);
                            }
                            else
                            {
                                act.AddOrUpdateReturnParamActual("Value", MFE.GetTextatPosition(Int32.Parse(act.LocateValueCalculated), Int32.Parse(act.ValueForDriver)));
                            }
                        }
                        else if (MFGD.LocateBy == eLocateBy.ByXY)
                        {
                            string XY = MFGD.LocateValueCalculated;

                            String[] XYSeparated = XY.Split(',');

                            int x = Int32.Parse(XYSeparated.ElementAt(0));
                            int y = Int32.Parse(XYSeparated.ElementAt(1));
                            if (x >= Coloumn || y >= Rows)
                            {
                                throw new Exception("X,Y out of bounds please use X/Y less than Rows/Columns configured in agent");
                            }
                            if (String.IsNullOrEmpty(act.ValueForDriver))
                            {
                                string MFText = MFE.GetTextatPosition(x, y, 50);
                                MFText = MFText.Split().ElementAt(0).ToString();
                                MFGD.AddOrUpdateReturnParamActual("Value", MFText);
                            }
                            else
                            {
                                act.AddOrUpdateReturnParamActual("Value", MFE.GetTextatPosition(x, y, Int32.Parse(act.ValueForDriver)));
                            }
                        }
                        break;

                    case ActMainframeGetDetails.eDetailsToFetch.GetDetailsFromText:

                        String[] MainFrameLines = MFE.screenText.Split('\n');
                        int      instance       = 1;
                        for (int i = 0; i < MainFrameLines.Length; i++)
                        {
                            locx = MainFrameLines[i].IndexOf(MFGD.ValueForDriver);
                            if (locx >= 0)
                            {
                                locy = i;
                                if (MFGD.TextInstanceType == ActMainframeGetDetails.eTextInstance.AllInstance)
                                {
                                    if (locy != -1)
                                    {
                                        act.AddOrUpdateReturnParamActualWithPath("CaretPosition", (locy * (MFColumns + 1) + locx).ToString(), instance.ToString());
                                        act.AddOrUpdateReturnParamActualWithPath("X", locx.ToString(), instance.ToString());
                                        act.AddOrUpdateReturnParamActualWithPath("Y", locy.ToString(), instance.ToString());
                                    }
                                }
                                else if (MFGD.TextInstanceType == ActMainframeGetDetails.eTextInstance.InstanceN)
                                {
                                    int k = Int32.Parse(MFGD.TextInstanceNumber);
                                    if (locy != -1 && instance == k)
                                    {
                                        act.AddOrUpdateReturnParamActual("CaretPosition", (locy * (MFColumns + 1) + locx).ToString());
                                        act.AddOrUpdateReturnParamActual("X", locx.ToString());
                                        act.AddOrUpdateReturnParamActual("Y", locy.ToString());
                                        break;
                                    }
                                }
                                else if (MFGD.TextInstanceType == ActMainframeGetDetails.eTextInstance.AfterCaretPosition)
                                {
                                    if (Int32.Parse(MFGD.LocateValueCalculated.ToString()) < (locy * (MFColumns + 1) + locx))
                                    {
                                        act.AddOrUpdateReturnParamActual("CaretPosition", (locy * (MFColumns + 1) + locx).ToString());
                                        act.AddOrUpdateReturnParamActual("X", locx.ToString());
                                        act.AddOrUpdateReturnParamActual("Y", locy.ToString());
                                        break;
                                    }
                                }
                                else
                                {
                                    if (locy != -1)
                                    {
                                        act.AddOrUpdateReturnParamActual("CaretPosition", (locy * (MFColumns + 1) + locx).ToString());
                                        act.AddOrUpdateReturnParamActual("X", locx.ToString());
                                        act.AddOrUpdateReturnParamActual("Y", locy.ToString());
                                        break;
                                    }
                                }
                            }
                            if (locy != -1)
                            {
                                instance++;
                            }
                        }

                        break;

                    case ActMainframeGetDetails.eDetailsToFetch.GetAllEditableFeilds:

                        XmlDocument    XD  = new XmlDocument();
                        XmlDeclaration dec = XD.CreateXmlDeclaration("1.0", null, null);
                        XD.AppendChild(dec);
                        XmlElement root = XD.CreateElement("EditableFields");
                        XD.AppendChild(root);

                        string CaretValuePair = @"<?xml version='1.0' encoding='UTF-8'?><nodes>";

                        XMLScreen XC = MFE.GetScreenAsXML();
                        foreach (XMLScreenField XSF in XC.Fields)
                        {
                            if (XSF.Attributes.Protected == true)
                            {
                                continue;
                            }
                            string node = "<node caret=\"" + XSF.Location.position.ToString() + "\" text=\"" + XSF.Text + "\"> </node>";

                            CaretValuePair = CaretValuePair + node;

                            XmlElement EditableField = XD.CreateElement("EditableField");
                            EditableField.SetAttribute("Caret", XSF.Location.position.ToString());
                            EditableField.SetAttribute("Text", XSF.Text);
                            root.AppendChild(EditableField);
                        }

                        act.AddOrUpdateReturnParamActual("Fields", XD.OuterXml);

                        break;

                    case ActMainframeGetDetails.eDetailsToFetch.GetCurrentScreenAsXML:

                        Open3270.TN3270.XMLScreen XMLS = MFE.GetScreenAsXML();
                        System.Xml.Serialization.XmlSerializer xsSubmit = new System.Xml.Serialization.XmlSerializer(typeof(Open3270.TN3270.XMLScreen));
                        System.IO.StringWriter sww    = new System.IO.StringWriter();
                        System.Xml.XmlWriter   writer = System.Xml.XmlWriter.Create(sww);

                        xsSubmit.Serialize(writer, XMLS);
                        String ScreenXML = sww.ToString();         // Your XML

                        act.AddOrUpdateReturnParamActual("ScreenXML", ScreenXML);

                        break;
                    }
                    break;

                case "GingerCore.Actions.MainFrame.ActMainframeSendKey":
                    ActMainframeSendKey MFSK = (ActMainframeSendKey)act;
                    MFE.SendKey(MFSK.KeyToSend);
                    break;

                case "GingerCore.Actions.MainFrame.ActMainframeSetText":
                    ActMainframeSetText MFST = (ActMainframeSetText)act;

                    switch (MFST.SetTextMode)
                    {
                    case ActMainframeSetText.eSetTextMode.SetSingleField:
                        if (MFST.LocateBy == eLocateBy.ByXY)
                        {
                            string XY = MFST.LocateValueCalculated;

                            String[] XYSeparated = XY.Split(',');

                            int x = Int32.Parse(XYSeparated.ElementAt(0));
                            int y = Int32.Parse(XYSeparated.ElementAt(1));
                            if (x >= Coloumn || y >= Rows)
                            {
                                throw new Exception("X,Y out of bounds please use X/Y less than Rows/Columns configured in agent");
                            }
                            MFE.SetCaretIndex(x, y);
                        }
                        else
                        {
                            MFE.SetCaretIndex(Int32.Parse(act.LocateValueCalculated));
                        }

                        MFE.SendText(act.ValueForDriver);

                        break;

                    case ActMainframeSetText.eSetTextMode.SetMultipleFields:

                        if (MFST.ReloadValue)
                        {
                            MFST.LoadCaretValueList();
                        }
                        foreach (ActInputValue AIV in MFST.CaretValueList)
                        {
                            MFE.SetCaretIndex(Int32.Parse(AIV.Param));
                            ValueExpression VE = new ValueExpression(this.Environment, this.BusinessFlow);
                            VE.Value = AIV.Value;
                            MFE.SendText(VE.ValueCalculated);
                        }

                        break;
                    }
                    if (MFST.SendAfterSettingText)
                    {
                        mDriverWindow.Refresh();
                        try
                        {
                            Thread.Sleep(DelayBwSetTextandSend * 1000);
                        }
                        catch
                        {
                            Thread.Sleep(3000);
                        }
                        MFE.SendKey(TnKey.Enter);
                    }
                    break;

                default:
                    throw new Exception("Action not Implemented");
                }

                mDriverWindow.Refresh();
            }
            catch (Exception e)
            {
                act.Status = Amdocs.Ginger.CoreNET.Execution.eRunStatus.Failed;
                act.ExInfo = e.Message;
            }
        }
Exemplo n.º 50
0
        protected override void Serialize(FileStream fileStream, TEntity entity)
        {
            var xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(TEntity));

            xmlSerializer.Serialize(fileStream, entity);
        }
Exemplo n.º 51
0
        public static T From <T>(XmlReader xmlReader, string originalXml)
        {
            var xs = new System.Xml.Serialization.XmlSerializer(typeof(T));

            return((T)xs.Deserialize(xmlReader));
        }
Exemplo n.º 52
0
        public static void PrintObject(Object obj)
        {
            System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(obj.GetType());

            x.Serialize(Console.Out, obj);
        }
Exemplo n.º 53
0
        private KeyContainerClass[] FindAuthorisedConnections()
        {
            //This might not work, especially in .NET 2.0 RTM, a shame but more
            //up to date users might as well use the feature if possible.
            Dictionary <string, string> configValues;

            try
            {
                FieldInfo fi = typeof(KeePass.App.Configuration.AceCustomConfig)
                               .GetField("m_vItems", BindingFlags.NonPublic | BindingFlags.Instance);
                configValues = (Dictionary <string, string>)fi.GetValue(_host.CustomConfig);
            }
            catch
            {
                return(null);
            }

            List <KeyContainerClass> keyContainers = new List <KeyContainerClass>();

            foreach (KeyValuePair <string, string> kvp in configValues)
            {
                if (kvp.Key.StartsWith("KeePassRPC.Key."))
                {
                    string username = kvp.Key.Substring(15);
                    byte[] serialisedKeyContainer = null;

                    // Assume config entry is encrypted but fall back to attempting direct deserialisation if something goes wrong

                    if (string.IsNullOrEmpty(kvp.Value))
                    {
                        return(null);
                    }
                    try
                    {
                        byte[] keyBytes = System.Security.Cryptography.ProtectedData.Unprotect(
                            Convert.FromBase64String(kvp.Value),
                            new byte[] { 172, 218, 37, 36, 15 },
                            System.Security.Cryptography.DataProtectionScope.CurrentUser);
                        serialisedKeyContainer = keyBytes;
                        System.Xml.Serialization.XmlSerializer mySerializer = new System.Xml.Serialization.XmlSerializer(typeof(KeyContainerClass));
                        using (MemoryStream ms = new System.IO.MemoryStream(serialisedKeyContainer))
                        {
                            keyContainers.Add((KeyContainerClass)mySerializer.Deserialize(ms));
                        }
                    }
                    catch (Exception)
                    {
                        try
                        {
                            serialisedKeyContainer = Convert.FromBase64String(kvp.Value);
                            System.Xml.Serialization.XmlSerializer mySerializer = new System.Xml.Serialization.XmlSerializer(typeof(KeyContainerClass));
                            using (MemoryStream ms = new MemoryStream(serialisedKeyContainer))
                            {
                                keyContainers.Add((KeyContainerClass)mySerializer.Deserialize(ms));
                            }
                        }
                        catch (Exception)
                        {
                            // It's not a valid entry so ignore it and move on
                            continue;
                        }
                    }
                }
            }
            return(keyContainers.ToArray());
        }
Exemplo n.º 54
0
        private static void LoadAllPlugins(string HelperDirectory = "")
        {
            string _RootDir = GameData.BaseDirectory;

            if (HelperDirectory != "")
            {
                _RootDir = HelperDirectory;
            }

            if (_RootDir.EndsWith("Data\\Plugins\\") == false)
            {
                _RootDir = _RootDir.EnsureDirectoryFormat() + "Data\\Plugins\\";
            }

            foreach (var file in System.IO.Directory.GetFiles(_RootDir, "*.dll", System.IO.SearchOption.AllDirectories))
            {
                string _PluginDirectory     = file.Substring(0, file.LastIndexOf("\\"));
                string _PluginDirectoryName = _PluginDirectory.Replace(_PluginDirectory.Substring(0, _PluginDirectory.LastIndexOf("\\")), "").Replace("\\", "");


                var _MainAssembly = System.Reflection.Assembly.LoadFile(file);
                AllAssemblies.Add(_MainAssembly);

                if (System.IO.File.Exists(_PluginDirectory.EnsureDirectoryFormat() + "pluginconfig.xml"))
                {
                    var _FileDataByteArray = Helper.IO.GetFile(_PluginDirectory.EnsureDirectoryFormat() + "pluginconfig.xml");
                    if (_FileDataByteArray == null)
                    {
                        continue;                               /*TODO LOG ERROR*/
                    }

                    System.Xml.Serialization.XmlSerializer _Serializer = new System.Xml.Serialization.XmlSerializer(typeof(Data.NGPluginConfig));
                    using (var _reader = new System.IO.StreamReader(new System.IO.MemoryStream(_FileDataByteArray)))
                    {
                        var _TmpData = (Data.NGPluginConfig)_Serializer.Deserialize(_reader);
                        if (_TmpData == null)
                        {
                            continue;
                        }
                        PluginConfiguration.Add(_PluginDirectoryName, _TmpData);
                    }
                    _Serializer        = null;
                    _FileDataByteArray = null;
                }

                foreach (var typ in _MainAssembly.ExportedTypes)
                {
                    if (typ.GetInterface("NebulaGames.RPGWorld.Interfaces.I_NGPlugin") != null)
                    {
                        Structs.CoreObject _CoreObj = new Structs.CoreObject();
                        _CoreObj.BaseAssembly  = _MainAssembly;
                        _CoreObj.Builtin       = false;
                        _CoreObj.InterfaceName = "NebulaGames.RPGWorld.Interfaces.I_NGPlugin";
                        _CoreObj.LoadPosition  = 1;
                        _CoreObj.BaseInstance  = _MainAssembly.CreateInstance(typ.FullName);

                        ObjectHierarchy.Add(_CoreObj);
                    }
                }
            }
        }
Exemplo n.º 55
0
        /// <summary>
        /// Carrega os dados do esquema contidos na stream de dados.
        /// </summary>
        /// <param name="inputStream"></param>
        /// <returns></returns>
        public static TypeSchema Load(System.IO.Stream inputStream)
        {
            var serializer = new System.Xml.Serialization.XmlSerializer(typeof(TypeSchema), Namespaces.Schema);

            return((TypeSchema)serializer.Deserialize(inputStream));
        }
Exemplo n.º 56
0
        ///<summary>Sends a request to HQ to update the Short Code Opt In status of this patient.  Can be sent silently without any feedback in the UI.
        ///</summary>
        private static bool TrySendToHq(string wirelessPhone, YN optIn, long patNum, long clinicNum, bool isSilent = false)
        {
            List <PayloadItem> listPayloadItems = new List <PayloadItem>()
            {
                new PayloadItem(wirelessPhone, "PhonePat"),
                new PayloadItem((int)optIn, "ShortCodeOptInInt"),
                new PayloadItem(patNum, "PatNum"),
                new PayloadItem(clinicNum, "ClinicNum"),
                new PayloadItem(false, "IsWebSchedNewPat"),
                new PayloadItem(isSilent, "IsSilentUpdate"),
            };
            string result = "";

            if (isSilent)
            {
                ODThread threadSilent = new ODThread((o) => WebServiceMainHQProxy.GetWebServiceMainHQInstance()
                                                     .SetSmsPatientPhoneOptIn(PayloadHelper.CreatePayload(listPayloadItems, eServiceCode.IntegratedTexting)));
                threadSilent.AddExceptionHandler((ex) => ex.DoNothing());
                threadSilent.Name = "ShortCodeOptIn";
                threadSilent.Start();
                return(true);
            }
            ODProgress.ShowAction(() => {
                result = WebServiceMainHQProxy.GetWebServiceMainHQInstance()
                         .SetSmsPatientPhoneOptIn(PayloadHelper.CreatePayload(listPayloadItems, eServiceCode.IntegratedTexting));
            });
            XmlDocument doc = new XmlDocument();

            doc.LoadXml(result);
            XmlNode node = doc.SelectSingleNode("//ListSmsToMobiles");

            if (node is null)
            {
                node = doc.SelectSingleNode("//Error");
                if (!(node is null))
                {
                    MessageBox.Show(Lan.g("ShortCodes", "An error occurred: ") + node.InnerText);
                }
                return(false);
            }
            List <SmsToMobile> listSmsToMobiles;

            using (XmlReader reader = XmlReader.Create(new System.IO.StringReader(node.InnerXml))) {
                System.Xml.Serialization.XmlSerializer xmlListSmsToMobileSerializer = new System.Xml.Serialization.XmlSerializer(typeof(List <SmsToMobile>));
                listSmsToMobiles = (List <SmsToMobile>)xmlListSmsToMobileSerializer.Deserialize(reader);
            }
            if (listSmsToMobiles == null)            //List should always be there even if it's empty.
            {
                MessageBox.Show(Lan.g("ShortCodes", "An error occurred: ") + node.InnerText);
                return(false);
            }
            //Should only be 0 or 1.
            if (listSmsToMobiles.Count > 0)
            {
                listSmsToMobiles.ForEach(x => x.DateTimeSent = DateTime.Now);
                SmsToMobiles.InsertMany(listSmsToMobiles);
                string message = $"{wirelessPhone} will shortly receive the following message{(listSmsToMobiles.Count>1 ? "s" : "")}:\n"
                                 + string.Join("\n", listSmsToMobiles.Select((x, i) => $"{i+1}) {x.MsgText}"));
                MessageBox.Show(message, "Appointment Texts");
            }
            //Local OptIn status for this patient will be updated by a Transmission from HQ, resulting from this call to SetSmsPatientPhoneOptIn().
            return(true);
        }
Exemplo n.º 57
0
        public Form1()
        {
            InitializeComponent();

            try
            {
                if (Process.GetProcessesByName(Path.GetFileNameWithoutExtension(AppDomain.CurrentDomain.FriendlyName)).Length > 1)
                {
                    MessageBox.Show("Launcher is already running.");
                    System.Environment.Exit(1);
                }

                string iniDirectoryPath = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\MurshunLauncher";

                xmlPath_textBox.Text = iniDirectoryPath + "\\MurshunLauncherServer.xml";

                if (!Directory.Exists(iniDirectoryPath))
                {
                    try
                    {
                        Directory.CreateDirectory(iniDirectoryPath);
                    }
                    catch
                    {
                        MessageBox.Show("Couldn't create a folder at " + iniDirectoryPath);
                    }
                }

                if (File.Exists(xmlPath_textBox.Text))
                {
                    ReadXmlFile();
                }
                else
                {
                    try
                    {
                        LauncherSettings = new MurshunLauncherXmlSettings();

                        System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(MurshunLauncherXmlSettings));

                        System.IO.FileStream writer = System.IO.File.Create(xmlPath_textBox.Text);
                        serializer.Serialize(writer, LauncherSettings);
                        writer.Close();

                        ReadXmlFile();
                    }
                    catch
                    {
                        MessageBox.Show("Saving xml settings failed.");
                    }
                }

                label3.Text = "Version " + launcherVersion;
            }
            catch (Exception e)
            {
                MessageBox.Show("Launcher crashed while initializing. Try running it as administrator.\n\n" + e.Message);
                System.Environment.Exit(1);
            }

            DownloadMissions();
        }
Exemplo n.º 58
0
        private void UserMap()
        {
            ScheduleViewModel scheduleViewModel =
                ((ScheduleViewModel)ViewModelPtrs[(int)ViewType.SCHED]);
            bool bCSV = false;

            Microsoft.Win32.OpenFileDialog fDialog = new Microsoft.Win32.OpenFileDialog();
            fDialog.Filter          = "User Map Files|*.xml;*.csv";
            fDialog.CheckFileExists = true;
            fDialog.Multiselect     = false;
            if (fDialog.ShowDialog() == true)
            {
                int lastDot = fDialog.FileName.LastIndexOf(".");

                if (lastDot != -1)
                {
                    string substr = fDialog.FileName.Substring(lastDot, 4);

                    if (substr == ".csv")
                    {
                        bCSV = true;

                        /*try
                        * {
                        *  string names = File.ReadAllText(fDialog.FileName);
                        *  string[] nameTokens = names.Split(',');
                        *  foreach (string name in nameTokens)
                        *  {
                        *      UsersList.Add(name);
                        *      scheduleViewModel.SchedList.Add(name);
                        *  }
                        * }
                        * catch (IOException ex)
                        * {
                        *  MessageBox.Show(ex.Message, "Zimbra Migration", MessageBoxButton.OK, MessageBoxImage.Exclamation);
                        * }*/
                        List <string[]> parsedData = new List <string[]>();
                        try
                        {
                            if (File.Exists(fDialog.FileName))
                            {
                                using (StreamReader readFile = new StreamReader(fDialog.FileName)) {
                                    string line;

                                    string[] row;
                                    while ((line = readFile.ReadLine()) != null)
                                    {
                                        row = line.Split(',');
                                        parsedData.Add(row);
                                    }
                                    readFile.Close();
                                }
                            }
                            else
                            {
                                MessageBox.Show(
                                    "There is no user information stored.Please enter some user info",
                                    "Zimbra Migration", MessageBoxButton.OK,
                                    MessageBoxImage.Error);
                            }
                        }
                        catch (Exception e)
                        {
                            string message = e.Message;
                        }
                        // for (int i = 1; i < parsedData.Count; i++)
                        {
                            string[] strres = new string[parsedData.Count];

                            Users tempuser = new Users();

                            try
                            {
                                for (int j = 0; j < parsedData.Count; j++)
                                {
                                    bool bFoundSharp = false;
                                    strres = parsedData[j];
                                    int num = strres.Count();
                                    for (int k = 0; k < num; k++)
                                    {
                                        if (strres[k].Contains("#"))
                                        {
                                            bFoundSharp = true;
                                            break;
                                        }
                                    }
                                    if (!bFoundSharp) // FBS bug 71933 -- 3/21/12
                                    {
                                        tempuser.UserName   = strres[0];
                                        tempuser.MappedName = strres[1];

                                        tempuser.ChangePWD = Convert.ToBoolean(strres[2]);
                                        // tempuser.PWDdefault = strres[3];
                                        // string result = tempuser.UserName + "," + tempuser.MappedName +"," + tempuser.ChangePWD + "," + tempuser.PWDdefault;
                                        string result = tempuser.Username + "," + tempuser.MappedName;

                                        Username   = strres[0];
                                        MappedName = strres[1];
                                        UsersViewModel uvm = new UsersViewModel(Username, MappedName);
                                        uvm.MustChangePassword = tempuser.ChangePWD;
                                        UsersList.Add(uvm);
                                        scheduleViewModel.SchedList.Add(new SchedUser(Username, false));
                                    }
                                }
                            }
                            catch (Exception)
                            {
                                MessageBox.Show("Incorrect .csv file format", "Zimbra Migration", MessageBoxButton.OK, MessageBoxImage.Error);
                                return;
                            }

                            EnableNext = (UsersList.Count > 0);
                        }
                        scheduleViewModel.EnableMigrate = (scheduleViewModel.SchedList.Count > 0);
                        scheduleViewModel.EnablePreview = scheduleViewModel.EnableMigrate;

                        // /
                        // Domain information is stored in the xml and not in  the usermap.
                        // will have to revisit

                        System.Xml.Serialization.XmlSerializer reader =
                            new System.Xml.Serialization.XmlSerializer(typeof(Config));
                        if (File.Exists(scheduleViewModel.GetConfigFile()))
                        {
                            System.IO.StreamReader fileRead = new System.IO.StreamReader(
                                scheduleViewModel.GetConfigFile());

                            Config Z11 = new Config();

                            Z11 = (Config)reader.Deserialize(fileRead);
                            fileRead.Close();
                            ZimbraDomain = Z11.UserProvision.DestinationDomain;
                            if (DomainList.Count > 0)
                            {
                                CurrentDomainSelection = (ZimbraDomain == null) ? 0 :
                                                         DomainList.IndexOf(ZimbraDomain);
                            }

                            else
                            {
                                DomainList.Add(ZimbraDomain);
                            }
                        }
                        scheduleViewModel.SetUsermapFile(fDialog.FileName);
                    }
                }
                if (!bCSV)
                {
                    MessageBox.Show("Only CSV files are supported", "Zimbra Migration",
                                    MessageBoxButton.OK, MessageBoxImage.Exclamation);
                }
            }
        }
Exemplo n.º 59
0
        internal static void PostRender(bool saveData = true)
        {
            if (saveData)
            {
                if (PrintJob.SelectedPrinter is AtumV20Printer || PrintJob.SelectedPrinter is AtumV15Printer)
                {
                    PrintJob.SelectedPrinter = new AtumV15Printer()
                    {
                        CorrectionFactorX         = PrintJob.SelectedPrinter.CorrectionFactorX,
                        CorrectionFactorY         = PrintJob.SelectedPrinter.CorrectionFactorY,
                        Description               = PrintJob.SelectedPrinter.Description,
                        DisplayName               = PrintJob.SelectedPrinter.DisplayName,
                        PrinterXYResolution       = PrintJob.SelectedPrinter.PrinterXYResolution,
                        Projectors                = PrintJob.SelectedPrinter.Projectors,
                        Properties                = PrintJob.SelectedPrinter.Properties,
                        TrapeziumCorrectionInputA = PrintJob.SelectedPrinter.TrapeziumCorrectionInputA,
                        TrapeziumCorrectionInputB = PrintJob.SelectedPrinter.TrapeziumCorrectionInputB,
                        TrapeziumCorrectionInputC = PrintJob.SelectedPrinter.TrapeziumCorrectionInputC,
                        TrapeziumCorrectionInputD = PrintJob.SelectedPrinter.TrapeziumCorrectionInputD,
                        TrapeziumCorrectionInputE = PrintJob.SelectedPrinter.TrapeziumCorrectionInputE,
                        TrapeziumCorrectionInputF = PrintJob.SelectedPrinter.TrapeziumCorrectionInputF,
                        TrapeziumCorrectionSideA  = PrintJob.SelectedPrinter.TrapeziumCorrectionSideA,
                        TrapeziumCorrectionSideB  = PrintJob.SelectedPrinter.TrapeziumCorrectionSideB,
                        TrapeziumCorrectionSideC  = PrintJob.SelectedPrinter.TrapeziumCorrectionSideC,
                        TrapeziumCorrectionSideD  = PrintJob.SelectedPrinter.TrapeziumCorrectionSideD,
                        TrapeziumCorrectionSideE  = PrintJob.SelectedPrinter.TrapeziumCorrectionSideE,
                        TrapeziumCorrectionSideF  = PrintJob.SelectedPrinter.TrapeziumCorrectionSideF,
                    };

                    PrintJob.SelectedPrinter.CreateProperties();
                    PrintJob.SelectedPrinter.CreateProjectors();
                    PrintJob.Option_TurnProjectorOff = PrintJob.Option_TurnProjectorOn = true;
                }
                else if (PrintJob.SelectedPrinter is AtumDLPStation5 || PrintJobManager.SelectedPrinter is LoctiteV10)
                {
                    PrintJob.SelectedPrinter = new AtumV15Printer()
                    {
                        CorrectionFactorX         = PrintJob.SelectedPrinter.CorrectionFactorX,
                        CorrectionFactorY         = PrintJob.SelectedPrinter.CorrectionFactorY,
                        Description               = PrintJob.SelectedPrinter.Description,
                        DisplayName               = PrintJob.SelectedPrinter.DisplayName,
                        PrinterXYResolution       = PrintJob.SelectedPrinter.PrinterXYResolution,
                        Projectors                = PrintJob.SelectedPrinter.Projectors,
                        Properties                = PrintJob.SelectedPrinter.Properties,
                        TrapeziumCorrectionInputA = PrintJob.SelectedPrinter.TrapeziumCorrectionInputA,
                        TrapeziumCorrectionInputB = PrintJob.SelectedPrinter.TrapeziumCorrectionInputB,
                        TrapeziumCorrectionInputC = PrintJob.SelectedPrinter.TrapeziumCorrectionInputC,
                        TrapeziumCorrectionInputD = PrintJob.SelectedPrinter.TrapeziumCorrectionInputD,
                        TrapeziumCorrectionInputE = PrintJob.SelectedPrinter.TrapeziumCorrectionInputE,
                        TrapeziumCorrectionInputF = PrintJob.SelectedPrinter.TrapeziumCorrectionInputF,
                        TrapeziumCorrectionSideA  = PrintJob.SelectedPrinter.TrapeziumCorrectionSideA,
                        TrapeziumCorrectionSideB  = PrintJob.SelectedPrinter.TrapeziumCorrectionSideB,
                        TrapeziumCorrectionSideC  = PrintJob.SelectedPrinter.TrapeziumCorrectionSideC,
                        TrapeziumCorrectionSideD  = PrintJob.SelectedPrinter.TrapeziumCorrectionSideD,
                        TrapeziumCorrectionSideE  = PrintJob.SelectedPrinter.TrapeziumCorrectionSideE,
                        TrapeziumCorrectionSideF  = PrintJob.SelectedPrinter.TrapeziumCorrectionSideF,
                        ProjectorResolutionX      = 1920,
                        ProjectorResolutionY      = 1080,
                    };

                    PrintJob.Option_TurnProjectorOff = PrintJob.Option_TurnProjectorOn = false;
                }


                //var printjobFolderName = Helpers.StringHelper.RemoveDiacritics(PrintJob.Name);
                //var slicePath = Path.Combine(PrintJob.SlicesPath, printjobFolderName);
                if (!PrintJob.SlicesPath.Contains(".zip"))
                {
                    PrintJob.SlicesPath = Path.Combine(PrintJob.SlicesPath, "slices.zip");
                }

                Debug.WriteLine("Total slice time: " + _stopWatch.ElapsedMilliseconds);
                //                Debug.WriteLine(DateTime.Now);

                MemoryHelpers.ForceGCCleanup();

                //save printjob xml file
                var pathPrinterJobXml = Path.Combine((new FileInfo(PrintJob.SlicesPath).Directory.FullName), "printjob.apj");
                var serializer        = new System.Xml.Serialization.XmlSerializer(typeof(DAL.Print.PrintJob));
                using (var streamWriter = new StreamWriter(pathPrinterJobXml, false))
                {
                    serializer.Serialize(streamWriter, PrintJob);
                }
            }

            try
            {
                _zipStream.Flush();
                _zipStream.Close();
                _zipStream.Dispose();

                _tempFileStream.Close();
            }
            catch
            {
            }

            RemoveModelClones();

            //copy org vectors to undopoints
            for (var object3dIndex = ObjectView.Objects3D.Count - 1; object3dIndex > 0; object3dIndex--)
            {
                var object3d = ObjectView.Objects3D[object3dIndex];

                if (!(object3d is GroundPane))
                {
                    var stlModel = object3d as STLModel3D;
                    stlModel.RevertTriangleSnapshotPoints();
                    stlModel.ClearSliceIndexes();

                    if (stlModel.SupportBasementStructure != null)
                    {
                        stlModel.SupportBasementStructure.MoveTranslation = new Vector3Class();
                    }

                    stlModel.UpdateBoundries();
                    stlModel.UpdateBinding();
                }
            }

            PrintJob.PostRenderCompleted = true;
            _cancelRendering             = false;
        }
Exemplo n.º 60
0
        public static void Serialize <T>(this  System.IO.StreamWriter input, T obj)
        {
            var xs = new System.Xml.Serialization.XmlSerializer(typeof(T), "http://schema.kanpekiitsolutions.com/");

            xs.Serialize(input, obj);
        }