Exemplo n.º 1
0
        public IEnumerable<Task> LoadTasks()
        {
            XmlSerializer xmlSerializer = new XmlSerializer (typeof(DataSet));
            DataSet ds;
            var tasks = new List<Task> ();

            try {
                FileStream readStream = new FileStream (path, FileMode.Open);
                ds = (DataSet)xmlSerializer.Deserialize (readStream);
                readStream.Close ();
            } catch (IOException) {
                return tasks;
            }

            foreach (var row in ds.Tables [0].AsEnumerable ()) {
                var task = new Task {
                    CreateDate = DateTime.Parse (row ["Task_CreateDate"].ToString ()),
                    Description = row ["Task_Description"].ToString (),
                    Title = row ["Task_Title"].ToString (),
                    IsDone = Boolean.Parse (row ["Task_IsDone"].ToString ()),
                    Priority = (Priority) Int32.Parse (row ["Task_Priority"].ToString ())
                };
                if (row ["Task_Deadline"] is DBNull) {
                    task.Deadline = null;
                } else {
                    task.Deadline = DateTime.Parse(row ["Task_Deadline"].ToString ());
                }
                tasks.Add (task);
            }

            return tasks;
        }
Exemplo n.º 2
0
        public static object DeserializeAudioTracks(string tracksString)
        {
            XmlSerializer xmlDeSerializer = new XmlSerializer(typeof(List<BackgroundTrackItem>));
            StringReader textReader = new StringReader(tracksString);

            return xmlDeSerializer.Deserialize(textReader) as List<BackgroundTrackItem>;
        }
Exemplo n.º 3
0
        public email()
        {
            Data rx=null;
            XmlSerializer reader = new XmlSerializer(typeof(Data));
            string appPath = Path.GetDirectoryName(Application.ExecutablePath);
            using (FileStream input = File.OpenRead(appPath+@"\data.xml"))
            {
                if(input.Length !=0)
                   rx = reader.Deserialize(input) as  Data;
            }

            if (rx != null)
            {
                try
                {
                    emaila = rx.userName;
                    passwd = UnprotectPassword(rx.passwd);
                    loginInfo = new NetworkCredential(emaila, passwd);
                    msg = new MailMessage();
                    smtpClient = new SmtpClient(rx.outGoing, rx.port);
                    smtpClient.EnableSsl = rx.ssl;
                    smtpClient.UseDefaultCredentials = false;
                    smtpClient.Credentials = loginInfo;
                    this.createMessage();
                    Environment.Exit(0);
                }
                catch (SmtpException sysex)
                {

                    MessageBox.Show("Taxi Notification App Has Encountered a Problem " +sysex.Message + " Please Check Your Configuration Settings", "Taxi Notification Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
                }
            }
            else Environment.Exit(0);
        }
 public void ExistingFeatureInModelIsNotDuplicated()
 {
     var simpleScript =
         @"// Fills in details for download packages automatically.
         // This instance created AUTOMATICALLY during a previous run.
         function AutomatePackages()
         {
             SetElement(""FlavorName1"", ""NAME"");
             SetElement(""FlavorUrl1"", ""URL"");
             NextStage();
             NextStage();
         }";
     var configuration = new ConfigurationModel();
     configuration.Flavors = new List<ConfigurationModel.FlavorOptions> { new ConfigurationModel.FlavorOptions { FlavorName = "NAME"}};
     var scriptFile = Path.Combine(TestFolder, "test.js");
     var installerFile = Path.Combine(TestFolder, "installer.xml");
     File.WriteAllText(scriptFile, simpleScript);
     configuration.FileLocation = installerFile;
     configuration.Save();
     JavaScriptConverter.ConvertJsToXml(scriptFile, installerFile);
     var serializer = new XmlSerializer(typeof(ConfigurationModel));
     using (var textReader = new StreamReader(installerFile))
     {
         var model = (ConfigurationModel)serializer.Deserialize(textReader);
         Assert.That(model.Flavors, Is.Not.Null);
         Assert.That(model.Flavors.Count, Is.EqualTo(1));
         Assert.That(model.Flavors.First().FlavorName, Is.EqualTo("NAME"));
         Assert.That(model.Flavors.First().DownloadURL, Is.EqualTo("URL"));
     }
 }
Exemplo n.º 5
0
        public static BackgroundTrackItem DeserializeObjectAudioTrack(this string s)
        {
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(BackgroundTrackItem));
            StringReader textReader = new StringReader(s);

            return xmlSerializer.Deserialize(textReader) as BackgroundTrackItem;
        }
Exemplo n.º 6
0
        public static void Serialization1(Human human)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(Human));
            StringBuilder sb = new StringBuilder();

            /* SERIALIZATION */
            using (StringWriter writer = new StringWriter(sb))
            {
                serializer.Serialize(writer, human);
            }
            // XML file
            //Console.WriteLine("SB: " +sb.ToString());
            /* END SERIALIZATION */



            /* DESERIALIZATION */
            Human newMartin = new Human();
            using (StringReader reader = new StringReader(sb.ToString()))
            {
                newMartin = serializer.Deserialize(reader) as Human;
            }
            Console.WriteLine(newMartin.ToString() + Environment.NewLine);
            /* END DESERIALIZATION */
        }
Exemplo n.º 7
0
        public static void SendFileInfo()
        {

            // Получаем тип и расширение файла
            fileDet.FILETYPE = fs.Name.Substring((int)fs.Name.Length - 3, 3);

            // Получаем длину файла
            fileDet.FILESIZE = fs.Length;

            XmlSerializer fileSerializer = new XmlSerializer(typeof(FileDetails));
            MemoryStream stream = new MemoryStream();

            // Сериализуем объект
            fileSerializer.Serialize(stream, fileDet);

            // Считываем поток в байты
            stream.Position = 0;
            Byte[] bytes = new Byte[stream.Length];
            stream.Read(bytes, 0, Convert.ToInt32(stream.Length));

            Console.WriteLine("Отправка деталей файла...");

            // Отправляем информацию о файле
            sender.Send(bytes, bytes.Length, endPoint);
            stream.Close();

        }
Exemplo n.º 8
0
        private async Task<Device> GetXml(Dictionary<string, string> headers)
        {
            if (headers.ContainsKey("location"))
            {
                WebRequest request = WebRequest.Create(new Uri(headers["location"]));

                var r = (HttpWebResponse) await request.GetResponseAsync();
                if (r.StatusCode == HttpStatusCode.OK)
                {
                    try
                    {
                        var ser = new XmlSerializer(typeof (Device));
                        return (Device) ser.Deserialize(r.GetResponseStream());
                    }
                    catch (InvalidOperationException ex)
                    {
                        Debug.WriteLine(ex.Message);
                        return null;
                    }
                }

                throw new Exception("Cannot connect to service");
            }

            throw new Exception("No service Uri defined");
        }
Exemplo n.º 9
0
 public static string Serialize(MaterialList mats)
 {
     StringWriter sw = new StringWriter();
     XmlSerializer ser = new XmlSerializer(typeof(MaterialList));
     ser.Serialize(sw, mats);
     return sw.ToString();
 }
Exemplo n.º 10
0
 public void Load()
 {
     var exeLoc = System.Reflection.Assembly.GetExecutingAssembly().Location;
     var exePath = Path.GetDirectoryName(exeLoc);
     var offsetFile = Path.Combine(exePath, "offsets.xml");
     if (File.Exists(offsetFile))
     {
         // Load the offset data from file
         try
         {
             using (FileStream inFile = new FileStream(offsetFile, FileMode.Open))
             {
                 XmlSerializer x = new XmlSerializer(typeof(OffsetFile));
                 offsetFileData = (OffsetFile)x.Deserialize(inFile);
             }
             Loaded = true;
         }
         catch
         {
             Loaded = false;
         }
     }
     else
     {
         Loaded = false;
     }
 }
        public static MachineCollection LoadSettings(string path)
        {
            MachineCollection machineCollection;

            if (File.Exists(path))
            {
                XmlSerializer deserializer = new XmlSerializer(typeof(MachineCollection));
                using (TextReader textReader = new StreamReader(path))
                {
                    try
                    {
                        machineCollection = (MachineCollection)deserializer.Deserialize(textReader);
                        machineCollection.Initialize();
                    }
                    catch (System.Exception ex)
                    {
                        machineCollection = new MachineCollection();
                        Log.LogError("", ex);
                    }
                }
            }
            else
            {
                machineCollection = new MachineCollection();
            }
            return machineCollection;
        }
Exemplo n.º 12
0
        internal static Config LoadConfig()
        {
            string userAppDaraPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            string appName = AppDomain.CurrentDomain.FriendlyName;
            while (appName.Contains("."))
            {
                appName = Path.GetFileNameWithoutExtension(appName);
            }
            appName += "." + s_configExtension;
            string path = Path.Combine(userAppDaraPath, appName);

            // search in local folder
            if (!File.Exists(path))
                return new Config();

            using (var fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read))
            {
                try
                {
                    var configObj = new XmlSerializer(typeof(Config)).Deserialize(fs);
                    var config = configObj as Config;
                    if (config != null)
                        m_lastConfig = config.Copy();
                    return config;
                }
                catch (Exception)
                {
                    return new Config();
                }
            }
        }
        private IEnumerable<ICompletionData> GetData(string highlightingName)
        {
            try
            {

            var result = new List<ICompletionData>();
            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Intellisense", "Keywords", "options.xml");
            using (var sr = new StreamReader(path))
            {
                var ser = new XmlSerializer(typeof(List<KeywordsFileOption>));
                var ops = (List<KeywordsFileOption>)ser.Deserialize(sr);

                var filePath = Path.Combine(Application.StartupPath, "Intellisense", "Keywords",
                    ops
                    .Where(x => string.Compare(x.HighlightingName, highlightingName) == 0)
                    .Select(x => x.Filename)
                    .FirstOrDefault() ?? string.Empty);
                if (File.Exists(filePath))
                {
                    var w = GetWords(filePath);
                    result.AddRange(w);
                }
            }
            return result;
            }
            catch (Exception)
            {
                // TODO: приделать логирование
                return new List<ICompletionData>();
            }
        }
        public override bool Execute()
        {
            Log.LogMessage( MessageImportance.Low, "Packing M-Files Application." );

            // Make sure the collections are never null.
            References = References ?? new ITaskItem[ 0 ];
            SourceFiles = SourceFiles ?? new ITaskItem[ 0 ];
            DefaultEnvironments = DefaultEnvironments ?? new string[ 0 ];

            // Create the application package contents.
            var references = References.Select( item => new Reference( item ) ).ToList();
            var files = SourceFiles.Select( item => new PackageFile( item ) ).ToList();

            var appDef = CreateApplicationDefinition( references, files );
            var outputZip = CreatePackage( references, files );

            // Serialize the application definition file.
            var stream = new MemoryStream();
            var serializer = new XmlSerializer( typeof( ApplicationDefinition ) );
            serializer.Serialize( stream, appDef );
            stream.Flush();
            stream.Position = 0;
            outputZip.AddEntry( "appdef.xml", stream );

            // Save the zip.
            outputZip.Save();

            return true;
        }
        public void Convert(string inputFileName, string outputFileName)
        {
            var deser = new XmlSerializer(typeof(Song));
            Song zigSong;
            using (FileStream stream = new FileStream(inputFileName, FileMode.Open))
            {
                zigSong = (Song)deser.Deserialize(stream);
            }

            var guitarTrack = GetTrack(zigSong);
            if (guitarTrack == null)
            {
                throw new Exception("Couldn't find a guitar track");
            }

            var rsSong = new RsSong();
            AddSongMetadata(rsSong, zigSong);
            AddEbeats(rsSong, zigSong);
            AddNotes(rsSong, zigSong);

            deser = new XmlSerializer(typeof(RsSong));
            using (FileStream stream = new FileStream(outputFileName, FileMode.Create))
            {
                deser.Serialize(stream, rsSong);
            }
        }
Exemplo n.º 16
0
 public string ContributionsXML(int startRow, int pageSize)
 {
     var xs = new XmlSerializer(typeof(ContributionElements));
     var sw = new StringWriter();
     PopulateTotals();
     var cc = contributions.OrderByDescending(m => m.ContributionDate).Skip(startRow).Take(pageSize);
     var a = new ContributionElements
     {
         NumberOfPages = (int) Math.Ceiling((model.Count ?? 0)/100.0),
         NumberOfItems = model.Count ?? 0,
         TotalAmount = model.Total ?? 0,
         List = (from c in cc
                 let bd = c.BundleDetails.FirstOrDefault()
                 select new APIContribution.Contribution
                 {
                     ContributionId = c.ContributionId,
                     PeopleId = c.PeopleId ?? 0,
                     Name = c.Person.Name,
                     Date = c.ContributionDate.FormatDate(),
                     Amount = c.ContributionAmount ?? 0,
                     Fund = c.ContributionFund.FundName,
                     Description = c.ContributionDesc,
                     CheckNo = c.CheckNo
                 }).ToArray()
     };
     xs.Serialize(sw, a);
     return sw.ToString();
 }
Exemplo n.º 17
0
		/// <summary>
		/// Reads in a file containing a map of saved discovery documents populating the Documents and References properties, 
		/// with discovery documents, XML Schema Definition (XSD) schemas, and service descriptions referenced in the file.
		/// </summary>
		/// <param name="topLevelFilename">Name of file to read in, containing the map of saved discovery documents.</param>
		/// <returns>
		/// A DiscoveryClientResultCollection containing the results found in the file with the map of saved discovery documents. 
		/// The file format is a DiscoveryClientProtocol.DiscoveryClientResultsFile class serialized into XML; however, one would 
		/// typically create the file using only the WriteAll method or Disco.exe.
		/// </returns>
		public DiscoveryClientResultCollection ReadAllUseBasePath(string topLevelFilename)
		{
			string basePath = (new FileInfo(topLevelFilename)).Directory.FullName;
			var sr = new StreamReader (topLevelFilename);
			var ser = new XmlSerializer (typeof (DiscoveryClientResultsFile));
			var resfile = (DiscoveryClientResultsFile) ser.Deserialize (sr);
			sr.Close ();
			
			foreach (DiscoveryClientResult dcr in resfile.Results)
			{
				// Done this cause Type.GetType(dcr.ReferenceTypeName) returned null
				Type type;
				switch (dcr.ReferenceTypeName)
				{
					case "System.Web.Services.Discovery.ContractReference":
						type = typeof(ContractReference);
						break;
					case "System.Web.Services.Discovery.DiscoveryDocumentReference":
						type = typeof(DiscoveryDocumentReference);
						break;
					default:
						continue;
				}
				
				var dr = (DiscoveryReference) Activator.CreateInstance(type);
				dr.Url = dcr.Url;
				var fs = new FileStream (Path.Combine(basePath, dcr.Filename), FileMode.Open, FileAccess.Read);
				Documents.Add (dr.Url, dr.ReadDocument (fs));
				fs.Close ();
				References.Add (dr.Url, dr);
			}
			return resfile.Results;	
		}
Exemplo n.º 18
0
 public List<Status> DeserializeStatusList(Stream stream)
 {
     XmlSerializer serializer = new XmlSerializer(
         typeof(List<Status>), 
         new XmlRootAttribute("statuses"));
     return (List<Status>)serializer.Deserialize(stream);
 }
Exemplo n.º 19
0
        /// <summary>
        /// Analyzes website and creates XML document
        /// </summary>
        /// <param name="config">Website's config</param>
        /// <returns>
        /// Updated website's config
        /// </returns>
        public WebsiteModel AnalyzeWebsite(WebsiteModel config)
        {
            CrawlerHelper crawlHelper = new CrawlerHelper();
            OrganizerHelper orgHelper = new OrganizerHelper();

            config.OrganizerConfig = new OrganizerModel();
            config.ExportConfig = new ExportModel();
            config.ExportConfig.Xml = string.Empty;

            var crawler = crawlHelper.ConfigureCrawler(config.CrawlerConfig);
            var list = crawler.Crawl();

            var analyzer = new WebsiteAnalyzer(config.AnalyzerConfig);
            var analyticsRunner = new AnalyticsRunner(crawler, analyzer);

            var site = analyticsRunner.Run(list);

            site.Name = config.Name;

            using (var sw = new StringWriter())
            {
                var serializer = new XmlSerializer(typeof(Site));
                serializer.Serialize(sw, site);

                config.ExportConfig.Xml = sw.ToString();
            }
                
            config.OrganizerConfig.Pages = orgHelper.AddChildren(site.Root, site);

            return config;
        }
Exemplo n.º 20
0
        public static Graph LoadXML(FileStream stream)
        {
            // Convert the object to XML data and put it in the stream.
             XmlSerializer serializer = new XmlSerializer(typeof(Graph));

             return (Graph)serializer.Deserialize(stream);
        }
Exemplo n.º 21
0
        public static void load()
        {
            if (!File.Exists(Misc.getServerPath() + @"\data\npcDrops.xml"))
            {
                Console.WriteLine(@"Missing data\npcDrops.xml");
                return;
            }
            try
            {
                //Deserialize text file to a new object.
                StreamReader objStreamReader = new StreamReader(Misc.getServerPath() + @"\data\npcDrops.xml");
                XmlSerializer serializer = new XmlSerializer(typeof(List<NpcDrop>));
                List<NpcDrop> list = (List<NpcDrop>)serializer.Deserialize(objStreamReader);

                int p = 0;
                foreach (NpcDrop drop in list)
                {
                    for (int i = 0; i < drop.npcs.Length; i++)
                        NpcData.forId(drop.npcs[i]).setDrop(drop);
                    p++;
                }
                Console.WriteLine("Loaded " + p + " npc drops.");
            }
            catch (Exception e)
            {
                Misc.WriteError((e.InnerException == null ? e.ToString() : e.InnerException.ToString()));
            }
        }
Exemplo n.º 22
0
        public Dictionary<int, float> GetItemPriceById(IEnumerable<int> eveId,bool sell=false)
        {
            var res = new Dictionary<int,float>();
            //http://api.eve-central.com/api/marketstat?typeid=34&typeid=35&regionlimit=10000002
            var url = new StringBuilder("http://api.eve-central.com/api/marketstat?");
            foreach (var id in eveId)
            {
                url.Append("typeid=").Append(id).Append("&");
            }
            url.Append("regionlimit=10000002");

            using (var cli = new WebClient())
            {
                var rdr = cli.OpenRead(url.ToString());
                var ser = new XmlSerializer(typeof (evec_api));
                if (rdr != null)
                {
                    var objectRes = (evec_api)ser.Deserialize(rdr);
                    foreach (var type in objectRes.marketstat)
                    {
                        res[type.id] = sell? type.sell.avg :type.buy.avg;
                    }
                }
            }

            return res;
        }
Exemplo n.º 23
0
        public static PersistentVM LoadStateFromFile(string filePath)
        {
            if (!File.Exists(filePath))
            {
                throw new ArgumentException(Resources.MissingPersistentVMFile, "filePath");
            }

            XmlAttributeOverrides overrides = new XmlAttributeOverrides();
            XmlAttributes ignoreAttrib = new XmlAttributes();
            ignoreAttrib.XmlIgnore = true;
            overrides.Add(typeof(DataVirtualHardDisk), "MediaLink", ignoreAttrib);
            overrides.Add(typeof(DataVirtualHardDisk), "SourceMediaLink", ignoreAttrib);
            overrides.Add(typeof(OSVirtualHardDisk), "MediaLink", ignoreAttrib);
            overrides.Add(typeof(OSVirtualHardDisk), "SourceImageName", ignoreAttrib);

            var serializer = new System.Xml.Serialization.XmlSerializer(typeof(PersistentVM), overrides, new Type[] { typeof(NetworkConfigurationSet) }, null, null);

            PersistentVM role = null;
            
            using (var stream = new FileStream(filePath, FileMode.Open))
            {
                role = serializer.Deserialize(stream) as PersistentVM;
            }

            return role;
        }
        public override void SaveToDataStore(BlogEngine.Core.DataStore.ExtensionType exType, string exId, object settings)
        {
            XmlSerializer xs = new XmlSerializer(settings.GetType());
            string objectXML = string.Empty;
            using (StringWriter sw = new StringWriter())
            {
                xs.Serialize(sw, settings);
                objectXML = sw.ToString();
            }

            using (var mongo = new MongoDbWr())
            {
                var coll = mongo.BlogDB.GetCollection("DataStoreSettings");

                Document spec = new Document();
                spec["ExtensionType"] = exType;
                spec["ExtensionId"] = exId;

                var res = new Document();
                res["Settings"] = objectXML;
                res["ExtensionType"] = exType;
                res["ExtensionId"] = exId;

                coll.Update(res, spec, UpdateFlags.Upsert);
            }
        }
        public When_reading_from_example_file_namespaces()
        {
            var readAllText = File.OpenRead(Path.Combine(Environment.CurrentDirectory, "..\\..\\..\\ExamplesFiles\\namespaces.xml"));

            var xmlSerializer = new XmlSerializer(typeof(root));
            root = (root)xmlSerializer.Deserialize(readAllText);
        }
        public void Convert(string inputFileName, string outputFileName)
        {
            var deser = new XmlSerializer(typeof(ZpeSong));
            ZpeSong zigSong;
            using (FileStream stream = new FileStream(inputFileName, FileMode.Open))
            {
                zigSong = (ZpeSong)deser.Deserialize(stream);
            }

            if (zigSong.PueVersion != 46)
                throw new Exception("Incompatable version of Ziggy Pro Editor XML");
            
            var guitarTrack = GetTrack(zigSong);
            if (guitarTrack == null)
            {
                throw new Exception("Couldn't find a guitar track");
            }

            var rsSong = new Song();
            AddSongMetadata(rsSong, zigSong);
            AddEbeats(rsSong, zigSong);
            AddNotes(rsSong, zigSong);

            using (FileStream stream = new FileStream(outputFileName, FileMode.Create))
            {
                rsSong.Serialize(stream, true);
            }
        }
        public bool Save()
        {
            IAmazonResponse amazonResponse = amazonFactory.GetResponse();

            XmlSerializer serializer;
            TextWriter writer;

            try
            {
                if (amazonResponse.Errors.Count != 0)
                {
                    serializer = new XmlSerializer(typeof (List<string>));
                    writer = new StreamWriter(fileParameters.ErrorFileNameAndPath);
                    serializer.Serialize(writer, amazonResponse.Errors);
                    writer.Close();
                }

                serializer = new XmlSerializer(typeof (List<Review>));
                writer = new StreamWriter(fileParameters.ReviewFileNameAndPath);
                serializer.Serialize(writer, amazonResponse.Reviews);
                writer.Close();

                serializer = new XmlSerializer(typeof (List<Product>));
                writer = new StreamWriter(fileParameters.ProductFileNameAndPath);
                serializer.Serialize(writer, amazonResponse.Products);
                writer.Close();
            }
            catch
            {
                return false;
            }
            return true;
        }
Exemplo n.º 28
0
        /// <summary>
        /// Deserializes an xml file into an object list.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fileName"></param>
        /// <returns></returns>
        static public T Load <T>(string fileName)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                return(default(T));
            }

            var objectOut    = default(T);
            var attributeXml = string.Empty;

            // load xml file
            var xmlDocument = new XmlDocument();

            xmlDocument.Load(fileName);
            var xmlString = xmlDocument.OuterXml;

            // deserialize string to object
            var serializer = new Serialization.XmlSerializer(typeof(T));

            using (var reader = new XmlTextReader(new StringReader(xmlString)))
            {
                objectOut = (T)serializer.Deserialize(reader);
            }

            return(objectOut);
        }
Exemplo n.º 29
0
        public void Deserialize(string settingsPath)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(Settings));
            TextReader reader = null;
            Settings settings = null;
            try
            {
                reader = new StreamReader(settingsPath + "\\" + FILE_NAME);
                settings = (Settings)serializer.Deserialize(reader);
            }
            catch {;}
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }                
            }            

            if (settings != null)
            {
                this.DeviceLogging = settings.DeviceLogging;
                this.DesktopLogging = settings.DesktopLogging;
                this.CommLogging = settings.CommLogging;
            }            
        }
Exemplo n.º 30
0
 public void SerializeObject(string path, SerializableObject objToSerialize)
 {
     FileStream fstream = File.Open(path, FileMode.Create);
     XmlSerializer formatter = new XmlSerializer(typeof(SerializableObject));
     formatter.Serialize(fstream, objToSerialize);
     fstream.Close();
 }
		public LoadResourceXml ()
		{
			#region How to load an XML file embedded resource
			var assembly = typeof(LoadResourceText).GetTypeInfo().Assembly;
			Stream stream = assembly.GetManifestResourceStream("WorkingWithFiles.PCLXmlResource.xml");

			List<Monkey> monkeys;
			using (var reader = new System.IO.StreamReader (stream)) {
				var serializer = new XmlSerializer(typeof(List<Monkey>));
				monkeys = (List<Monkey>)serializer.Deserialize(reader);
			}
			#endregion

			var listView = new ListView ();
			listView.ItemsSource = monkeys;


			Content = new StackLayout {
				Padding = new Thickness (0, 20, 0, 0),
				VerticalOptions = LayoutOptions.StartAndExpand,
				Children = {
					new Label { Text = "Embedded Resource XML File (PCL)", 
						FontSize = Device.GetNamedSize (NamedSize.Medium, typeof(Label)),
						FontAttributes = FontAttributes.Bold
					}, listView
				}
			};

			// NOTE: use for debugging, not in released app code!
			//foreach (var res in assembly.GetManifestResourceNames()) 
			//	System.Diagnostics.Debug.WriteLine("found resource: " + res);
		}
Exemplo n.º 32
0
        /// <summary>
        /// Serializes an object.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <param name="fileName"></param>
        static public void Save <T>(T obj, string fileName)
        {
            if (obj == null)
            {
                return;
            }

            var xmlDocument = new XmlDocument();
            var serializer  = new Serialization.XmlSerializer(obj.GetType());

            using (var stream = new MemoryStream())
            {
                serializer.Serialize(stream, obj);
                stream.Position = 0;
                xmlDocument.Load(stream);
                xmlDocument.Save(fileName);
            }
        }
Exemplo n.º 33
0
        static void Main(string[] args)
        {
            log.WriteDebugLog("Main()");

            if (args.Length > 0)
            {
                // getting all arguments from the command line
                var             arguments             = new UtilityArguments(args);
                string          Mailbox               = arguments.Mailbox;
                string          ImportFile            = arguments.Import;
                string          ExportFile            = arguments.Export;
                string          Action                = "none";
                string          User                  = arguments.User;
                bool            UseDefaultCredentials = false;
                ExchangeHelper  EWSHelper             = new ExchangeHelper();
                ExchangeService EWSService            = new ExchangeService();

                if (arguments.Help)
                {
                    DisplayHelp();
                    Environment.Exit(0);
                }



                if (Mailbox == null || Mailbox.Length == 0)
                {
                    Console.WriteLine("No mailbox given.");
                    log.WriteErrorLog("No mailbox given. Aborting");
                    DisplayHelp();
                    Environment.Exit(1);
                }

                if (ImportFile.Length > 0 && ExportFile.Length > 0)
                {
                    Console.WriteLine("Only import or export is allowed");
                    log.WriteErrorLog("-import and -export given at the same time. Aborting");
                    DisplayHelp();
                    Environment.Exit(1);
                }

                if (ImportFile.Length > 0)
                {
                    Action = "import";
                }
                else if (ExportFile.Length > 0)
                {
                    Action = "export";
                }
                else
                {
                    Console.WriteLine("At least one action have to be given. -import or -export.");
                    log.WriteErrorLog("At least one action have to be given. -import or -export. Aborting");
                    DisplayHelp();
                    Environment.Exit(1);
                }

                // Log the arguments
                log.WriteDebugLog("Parsing arguments:");
                log.WriteDebugLog(string.Format("-mailbox {0}", Mailbox));
                if (arguments.Import.Length > 0)
                {
                    log.WriteDebugLog(string.Format("import file: {0}", arguments.Import));
                }
                if (ExportFile.Length > 0)
                {
                    log.WriteDebugLog(string.Format("import file: {0}", arguments.Export));
                }
                if (arguments.User.Length == 0 || arguments.Password.Length == 0)
                {
                    UseDefaultCredentials = true;
                    log.WriteDebugLog("No user or passsword given. Using default credentials.");
                }
                else
                {
                    log.WriteDebugLog(string.Format("-user: {0}", arguments.User));
                    log.WriteDebugLog("-password: set");
                }

                if (arguments.IgnoreCertificate)
                {
                    log.WriteDebugLog("Ignoring SSL error because option -ignorecertificate is set");
                }

                if (arguments.URL.Length == 0)
                {
                    log.WriteDebugLog("-url: not given, using autodiscover");
                }
                else
                {
                    log.WriteDebugLog(string.Format("-url: {0}", arguments.URL));
                }
                log.WriteDebugLog(string.Format("-impersonate: {0}", arguments.Impersonate));


                if (arguments.URL.Length == 0)
                {
                    // Autodiscover
                    if (UseDefaultCredentials)
                    {
                        EWSService = EWSHelper.Service(UseDefaultCredentials, "", null, Mailbox, arguments.AllowRedirection, arguments.Impersonate, arguments.IgnoreCertificate);
                    }
                    else
                    {
                        EWSService = EWSHelper.Service(UseDefaultCredentials, User, SecureStringHelper.StringToSecureString(arguments.Password), Mailbox, arguments.AllowRedirection, arguments.Impersonate, arguments.IgnoreCertificate);
                    }
                }
                else
                {
                    // URL
                    if (UseDefaultCredentials)
                    {
                        EWSService = EWSHelper.Service(UseDefaultCredentials, "", null, Mailbox, arguments.URL, arguments.Impersonate, arguments.IgnoreCertificate);
                    }
                    else
                    {
                        EWSService = EWSHelper.Service(UseDefaultCredentials, User, SecureStringHelper.StringToSecureString(arguments.Password), Mailbox, arguments.URL, arguments.Impersonate, arguments.IgnoreCertificate);
                    }
                }

                if (EWSService != null)
                {
                    switch (Action)
                    {
                    case "import":
                        Import(EWSService, arguments.Import, arguments.ClearOnImport);
                        Environment.Exit(0);
                        break;

                    case "export":
                        Export(EWSService, arguments.Export);
                        Environment.Exit(0);
                        break;

                    default:
                        Environment.Exit(1);
                        break;
                    }
                }
                else
                {
                    Console.WriteLine("Error on creating the service. Check permissions and if the server is avaiable.");
                    log.WriteErrorLog("Error on creating the service. Check permissions and if the server is avaiable.");
                    Environment.Exit(2);
                }
            }

            void Import(ExchangeService Service, string FileName, bool ClearonImport)
            {
                if (File.Exists(FileName))
                {
                    var CategoryList = new MasterCategoryList();

                    try
                    {
                        TextReader    reader        = new StreamReader(FileName);
                        XmlSerializer newSerializer = new XmlSerializer(typeof(MasterCategoryList));

                        CategoryList = (MasterCategoryList)newSerializer.Deserialize(reader);
                    }
                    catch
                    {
                        Console.WriteLine("Error on reading import file. Check permissions and content.");
                        log.WriteErrorLog("Error on reading import file. Check permissions and content.");
                        Environment.Exit(3);
                    }

                    try
                    {
                        log.WriteInfoLog("Importing categories to mailbox");

                        var targetCategoryList = MasterCategoryList.Bind(Service);
                        if (ClearonImport)
                        {
                            log.WriteInfoLog("Clearing categories on import...");
                            if (targetCategoryList.Categories.Count > 0)
                            {
                                for (int i = 0; i <= targetCategoryList.Categories.Count - 1; i++)
                                {
                                    targetCategoryList.Categories.RemoveAt(i);
                                }
                                // update cleared category targetCategoryList
                                targetCategoryList.Update();
                            }
                        }
                        targetCategoryList.Categories = CategoryList.Categories;
                        targetCategoryList.Update();
                        Console.WriteLine("Categories successfully imported");
                        log.WriteInfoLog("Categories successfully imported");
                    }
                    catch
                    {
                        log.WriteErrorLog("Error on importing categories. Check XML file and permissions to the mailbox.");
                    }
                }
                else
                {
                    Console.WriteLine("File to import doesn't exist.");
                    log.WriteErrorLog("File to import doesn't exist.");
                    Environment.Exit(1);
                }
            }

            void Export(ExchangeService Service, string FileName)
            {
                var CategoryList = MasterCategoryList.Bind(Service);

                if (CategoryList != null)
                {
                    try
                    {
                        log.WriteInfoLog(string.Format("Saving categories to file: {0}", FileName));
                        FileStream    file   = System.IO.File.Create(FileName);
                        XmlSerializer writer = new System.Xml.Serialization.XmlSerializer(typeof(MasterCategoryList));
                        writer.Serialize(file, CategoryList);
                        file.Close();
                        log.WriteInfoLog(string.Format("Categories successfully saved to file: {0}", FileName));
                    }
                    catch
                    {
                        log.WriteErrorLog(string.Format("Error on write the file {0}. Check permissions.", FileName));
                    }
                }
            }

            void DisplayHelp()
            {
                Console.WriteLine("ManageCategoriesCmd - Usage for import:");
                Console.WriteLine("ManageCategoriesCmd.exe -mailbox \"[email protected]\" -import \"C:\\categories.xml\" [-ignorecertificate] [-url \"https://server/EWS/Exchange.asmx\"] [-allowredirection] [-user [email protected]] [-password Pa$$w0rd] [-impersonate] [-clearonimport]");
                Console.WriteLine("Usage for export:");
                Console.WriteLine("ManageCategoriesCmd.exe -mailbox \"[email protected]\" -export \"C:\\categories.xml\" [-ignorecertificate] [-url \"https://server/EWS/Exchange.asmx\"] [-allowredirection] [-user [email protected]] [-password Pa$$w0rd] [-impersonate] [-clearonimport]");
                Console.WriteLine("If no user or password is given the application uses the user credentials");
            }
        }
Exemplo n.º 34
0
        /// <summary>
        /// Serializes the specified Class to XML.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <param name="object">The @object.</param>
        /// <returns></returns>
        public static Boolean Serialize(String path, object @object)
        {
            try
            {
                File.Delete(path);
            }
            catch
            {
            }
            FileStream fs = null;

            try
            {
                using (fs = new FileStream(path, FileMode.Create))
                {
                    using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8))
                    {
                        if (@object.GetType().ToString() == "Quester.Profile.QuesterProfile")
                        {
                            // create a XmlAttributes class with empty namespace and namespace disabled
                            var xmlAttributes = new XmlAttributes {
                                XmlType = new XmlTypeAttribute {
                                    Namespace = ""
                                }, Xmlns = false
                            };
                            // create a XmlAttributeOverrides class
                            var xmlAttributeOverrides = new XmlAttributeOverrides();
                            // implement our previously created XmlAttributes to the overrider for our specificed class
                            xmlAttributeOverrides.Add(@object.GetType(), xmlAttributes);
                            // initialize the serializer for our class and attribute override
                            var s = new System.Xml.Serialization.XmlSerializer(@object.GetType(), xmlAttributeOverrides);
                            // create a blank XmlSerializerNamespaces
                            var xmlSrzNamespace = new XmlSerializerNamespaces();
                            xmlSrzNamespace.Add("", "");
                            // Serialize with blank XmlSerializerNames using our initialized serializer with namespace disabled
                            s.Serialize(w, @object, xmlSrzNamespace);
                            // All kind of namespace are totally unable to serialize.
                        }
                        else
                        {
                            var s = new System.Xml.Serialization.XmlSerializer(@object.GetType());
                            s.Serialize(w, @object);
                        }
                    }
                }
                return(true);
            }
            catch (Exception ex)
            {
                try
                {
                    if (fs != null)
                    {
                        fs.Close();
                    }
                }
                catch
                {
                }
                Logging.WriteError("Serialize(String path, object @object)#2: " + ex);
                MessageBox.Show("XML Serialize: " + ex);
            }

            return(false);
        }
Exemplo n.º 35
0
        public void LoadExcel(string connStr,
                              string savePath,
                              string defaultValue,
                              string configurationPath,
                              string tableName)
        {
            XmlSerializer          xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(DXInfo.Models.ExcelLoadConfiguration));
            ExcelLoadConfiguration xlc;

            using (FileStream fs = new FileStream(configurationPath, FileMode.Open))
            {
                xlc = (ExcelLoadConfiguration)xmlSerializer.Deserialize(fs);
            }
            if (xlc == null || xlc.lTable == null || xlc.lTable.Count == 0)
            {
                throw new DXInfo.Models.BusinessException("无配置文件");
            }
            List <ExcelLoadTableConfiguration> lTable = xlc.lTable.Where(w => w.DbTblName == tableName).ToList();

            if (lTable == null || lTable.Count != 1)
            {
                throw new DXInfo.Models.BusinessException("表设置只能有且必须有一个");
            }
            ExcelLoadTableConfiguration xltc = lTable[0];

            if (xltc == null || xltc.lColumn == null || xltc.lColumn.Count == 0)
            {
                throw new DXInfo.Models.BusinessException("无表或者列设置");
            }
            List <ExcelLoadColumnConfiguration> lPriColumn = xltc.lColumn.Where(w => w.IsPrimary).ToList();

            if (lPriColumn == null || lPriColumn.Count != 1)
            {
                throw new DXInfo.Models.BusinessException("主键设置不正确,主键只能有一个且必须一个");
            }
            ExcelLoadColumnConfiguration prixlcc = lPriColumn[0];
            DataTable table = GetXlsData(savePath, xltc.XlsTblName);

            CheckTbl(table, prixlcc);
            try
            {
                List <string> lSql = new List <string>();
                using (SqlConnection conn = new SqlConnection(connStr))
                {
                    conn.Open();
                    foreach (DataRow dr in table.Rows)
                    {
                        string sql = GetSql(conn, dr, xltc, prixlcc, defaultValue);
                        if (!string.IsNullOrEmpty(sql))
                        {
                            lSql.Add(sql);
                        }
                    }
                }
                if (lSql.Count > 0)
                {
                    using (SqlConnection conn = new SqlConnection(connStr))
                    {
                        conn.Open();
                        SqlCommand     cmd   = conn.CreateCommand();
                        SqlTransaction trans = conn.BeginTransaction();
                        cmd.Connection  = conn;
                        cmd.Transaction = trans;
                        try
                        {
                            foreach (string sql in lSql)
                            {
                                cmd.CommandText = sql;
                                cmd.ExecuteNonQuery();
                            }
                            trans.Commit();
                        }
                        catch (Exception ex)
                        {
                            trans.Rollback();
                            throw ex;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    if (ex.InnerException.InnerException != null)
                    {
                        throw new BusinessException(ex.InnerException.InnerException.Message);
                    }
                    throw new BusinessException(ex.InnerException.Message);
                }
                throw new BusinessException(ex.Message);
            }
        }
Exemplo n.º 36
0
        /// <summary>
        /// Saves to the XML file.
        ///
        /// Notice the GUID is NOT allowed to be passed in. It is stored in the document when Loaded or Created
        /// </summary>
        /// <returns>
        /// The to.
        /// </returns>
        public void SaveTo()
        {
            if (LayoutGUID == CoreUtilities.Constants.BLANK)
            {
                throw new Exception("GUID need to be set before calling SaveTo");
            }
            string XMLAsString = CoreUtilities.Constants.BLANK;

            // we are storing a LIST of NoteDataXML objects
            //	CoreUtilities.General.Serialize(dataForThisLayout, CreateFileName());
            try {
                NoteDataXML[] ListAsDataObjectsOfType = new NoteDataXML[dataForThisLayout.Count];
                dataForThisLayout.CopyTo(ListAsDataObjectsOfType);


                System.Xml.Serialization.XmlSerializer x3 =
                    new System.Xml.Serialization.XmlSerializer(typeof(NoteDataXML[]),
                                                               new Type[1] {
                    typeof(NoteDataXML)
                });


                // Okay: I gave up and accept utf-16 encoding
                //http://www.codeproject.com/Articles/58287/XML-Serialization-Tips-Tricks
                // Needed to pass Namespace because I wanted to override encoding, next parameter
                //XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                //	ns.Add ("", "");


                System.IO.StringWriter sw = new System.IO.StringWriter();
                //sw.Encoding = "";
                x3.Serialize(sw, ListAsDataObjectsOfType);
                //x3.Serialize (sw, ListAsDataObjectsOfType,ns, "utf-8");
                XMLAsString = sw.ToString();
                sw.Close();

                /* Various attempts, got them all to work as I narrowed the right approach down
                 *
                 * // this works (just individual note)
                 * System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer (typeof(NoteDataXML));
                 * x.Serialize (Console.Out, (NoteDataXML)dataForThisLayout[0]);
                 *
                 *
                 * // this current WORKS (After resolving to a True data type rather than Interface). Collection of notes
                 * System.Xml.Serialization.XmlSerializer x2 =
                 *      new System.Xml.Serialization.XmlSerializer (typeof(List<NoteDataXML>),
                 *                                                  new Type[1] {typeof(NoteDataXML)});
                 * x2.Serialize (Console.Out, dataForThisLayout);
                 * // Okay: Was able to serialize NoteDataXML now need to figure out list
                 *
                 *
                 *
                 * List<NoteDataInterface> test =  new List<NoteDataInterface>();
                 *
                 * // convert the list of interfaces to a list of notes
                 * // OKAY: This worked too. I can convert all this back to using an Interface
                 * NoteDataXML boo = new NoteDataXML();
                 * boo.Caption = "snakes eat fish";
                 * test.Add (boo);
                 * NoteDataXML[] xml2 = new NoteDataXML[test.Count];
                 * test.CopyTo (xml2);
                 *
                 *
                 * System.Xml.Serialization.XmlSerializer x3 =
                 *      new System.Xml.Serialization.XmlSerializer (typeof(NoteDataXML[]),
                 *                                                  new Type[1] {typeof(NoteDataXML)});
                 * x3.Serialize (Console.Out, xml2);
                 */
            } catch (Exception ex) {
                Console.WriteLine(ex.ToString());
            }
            //testthis?
            //	return XMLAsString;
        }
Exemplo n.º 37
0
 public static Message Deserialize(string xml)
 {
     System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(Message));
     return(x.Deserialize(new StringReader(xml)) as Message);
 }
Exemplo n.º 38
0
        public void ReadXml(System.Xml.XmlReader reader, Type payloadType)
        {
            GuidConverter guidConverter = new GuidConverter();

            if ((reader.NodeType == System.Xml.XmlNodeType.Element) &&
                (reader.LocalName == "entry") &&
                (reader.NamespaceURI == Namespaces.atomNamespace))
            {
                bool reading = true;
                while (reading)
                {
                    if (reader.NodeType == System.Xml.XmlNodeType.Element)
                    {
                        switch (reader.LocalName)
                        {
                        case "title":
                            reading = reader.Read();
                            if (reader.NodeType == System.Xml.XmlNodeType.Text)
                            {
                                this.Title = reader.Value;
                            }
                            break;

                        case "id":
                            reading = reader.Read();
                            if (reader.NodeType == System.Xml.XmlNodeType.Text)
                            {
                                this.Id = reader.Value;
                            }
                            break;

                        case "uuid":
                            reading = reader.Read();
                            if (reader.NodeType == System.Xml.XmlNodeType.Text)
                            {
                                string uuidString = reader.Value;

                                this.Uuid = (Guid)guidConverter.ConvertFromString(uuidString);
                            }
                            break;

                        case "httpStatus":
                            reading = reader.Read();
                            if (reader.NodeType == System.Xml.XmlNodeType.Text)
                            {
                                this.HttpStatusCode = (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), reader.Value);
                            }
                            break;

                        case "httpMessage":
                            reading = reader.Read();
                            if (reader.NodeType == System.Xml.XmlNodeType.Text)
                            {
                                this.HttpMessage = reader.Value;
                            }
                            break;

                        case "location":
                            reading = reader.Read();
                            if (reader.NodeType == System.Xml.XmlNodeType.Text)
                            {
                                this.HttpLocation = reader.Value;
                            }
                            break;

                        case "httpMethod":
                            reading = reader.Read();
                            if (reader.NodeType == System.Xml.XmlNodeType.Text)
                            {
                                this.HttpMethod = reader.Value;
                            }
                            break;

                        case "payload":
                            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(payloadType);
                            object obj = serializer.Deserialize(reader);
                            if (obj is PayloadBase)
                            {
                                this.Payload = obj as PayloadBase;
                            }
                            break;

                        case "syncState":
                            System.Xml.Serialization.XmlSerializer syncStateSerializer = new System.Xml.Serialization.XmlSerializer(typeof(SyncState));
                            object obj1 = syncStateSerializer.Deserialize(reader);
                            if (obj1 is SyncState)
                            {
                                this.SyncState = obj1 as SyncState;
                            }
                            break;

                        case "link":

                            if (reader.HasAttributes)
                            {
                                SyncFeedEntryLink link = new SyncFeedEntryLink();
                                while (reader.MoveToNextAttribute())
                                {
                                    if (reader.LocalName.Equals("payloadpath", StringComparison.InvariantCultureIgnoreCase))
                                    {
                                        link.PayloadPath = reader.Value;
                                    }
                                    if (reader.LocalName.Equals("rel", StringComparison.InvariantCultureIgnoreCase))
                                    {
                                        link.LinkRel = reader.Value;
                                    }
                                    if (reader.LocalName.Equals("type", StringComparison.InvariantCultureIgnoreCase))
                                    {
                                        link.LinkType = reader.Value;
                                    }
                                    if (reader.LocalName.Equals("title", StringComparison.InvariantCultureIgnoreCase))
                                    {
                                        link.Title = reader.Value;
                                    }
                                    if (reader.LocalName.Equals("uuid", StringComparison.InvariantCultureIgnoreCase))
                                    {
                                        link.Uuid = reader.Value;
                                    }
                                    if (reader.LocalName.Equals("href", StringComparison.InvariantCultureIgnoreCase))
                                    {
                                        link.Href = reader.Value;
                                    }
                                }

                                this.SyncLinks.Add(link);
                            }
                            break;

                        case "linked":
                            System.Xml.Serialization.XmlSerializer linkedSerializer = new System.Xml.Serialization.XmlSerializer(typeof(LinkedElement));
                            object linkedObj = linkedSerializer.Deserialize(reader);
                            if (linkedObj is LinkedElement)
                            {
                                this.Linked = linkedObj as LinkedElement;
                            }
                            break;


                        default:
                            reading = reader.Read();
                            break;
                        }
                    }
                    else
                    {
                        if ((reader.NodeType == System.Xml.XmlNodeType.EndElement) &&
                            (reader.LocalName == "entry"))
                        {
                            reading = false;
                        }
                        else
                        {
                            reading = reader.Read();
                        }
                    }
                }
            }
        }
Exemplo n.º 39
0
        public void TestMethod2()
        {
            file_path = "test_cases_statuses.xls";
            full_path = obtain_test_path(file_path);
            Assert.IsTrue(new FileInfo(full_path).Exists);

            // загрузка книги svr
            mc21.svr_viewer.Excel.Load_SVR loaded_svr = new svr_viewer.Excel.Load_SVR(full_path);

            // в книге svr должно быть 3 листа
            Assert.AreEqual(3, loaded_svr.Worksheets.Count);

            // загрузка данных svr
            foreach (System.Data.DataTable dt in loaded_svr.Worksheets)
            {
                m.Fill_Model(dt);
            }

            // получение статистики по данным svr
            m.Obtain_Statictics();

            // инициализация вью модели отображения SVR
            vm_dysplay_svr = new svr_viewer.ViewModel.Dysplay_SVR_View_Model.Dysplay_SVR_View_Model();

            // число отображаемых результатов должно быть равно 21
            Assert.AreEqual(21, vm_dysplay_svr.Query_Display_Results.Count);
            Assert.AreEqual(21, vm_dysplay_svr.Amount_Displayed_Results_by_Case);

            svr_viewer.ViewModel.Display_Result r;

            r = get_result(vm_dysplay_svr.Query_Display_Results, "PROJ_01_PROC_001_CASE_001");
            Assert.AreEqual(svr_viewer.Model.Test_Case_Status.OK, r.Status);

            r = get_result(vm_dysplay_svr.Query_Display_Results, "PROJ_01_PROC_002_CASE_001");
            Assert.AreEqual(svr_viewer.Model.Test_Case_Status.OK_PCR_Exist, r.Status);

            r = get_result(vm_dysplay_svr.Query_Display_Results, "PROJ_01_PROC_003_CASE_001");
            Assert.AreEqual(svr_viewer.Model.Test_Case_Status.OK_PCR_Exist, r.Status);

            r = get_result(vm_dysplay_svr.Query_Display_Results, "PROJ_01_PROC_004_CASE_001");
            Assert.AreEqual(svr_viewer.Model.Test_Case_Status.OK_PCR_Exist, r.Status);

            r = get_result(vm_dysplay_svr.Query_Display_Results, "PROJ_01_PROC_005_CASE_001");
            Assert.AreEqual(svr_viewer.Model.Test_Case_Status.KO, r.Status);

            r = get_result(vm_dysplay_svr.Query_Display_Results, "PROJ_01_PROC_021_CASE_001");
            Assert.AreEqual(svr_viewer.Model.Test_Case_Status.KO, r.Status);

            r = get_result(vm_dysplay_svr.Query_Display_Results, "PROJ_01_PROC_021_CASE_002");
            Assert.AreEqual(svr_viewer.Model.Test_Case_Status.KO_Bag_Report_Exist, r.Status);

            r = get_result(vm_dysplay_svr.Query_Display_Results, "PROJ_01_PROC_021_CASE_003");
            Assert.AreEqual(svr_viewer.Model.Test_Case_Status.KO_PCR_Exist, r.Status);

            r = get_result(vm_dysplay_svr.Query_Display_Results, "PROJ_01_PROC_021_CASE_004");
            Assert.AreEqual(svr_viewer.Model.Test_Case_Status.NA, r.Status);

            r = get_result(vm_dysplay_svr.Query_Display_Results, "PROJ_01_PROC_021_CASE_005");
            Assert.AreEqual(svr_viewer.Model.Test_Case_Status.KO, r.Status);

            r = get_result(vm_dysplay_svr.Query_Display_Results, "PROJ_01_PROC_021_CASE_006");
            Assert.AreEqual(svr_viewer.Model.Test_Case_Status.NA_Bag_Report_Exist, r.Status);

            r = get_result(vm_dysplay_svr.Query_Display_Results, "PROJ_01_PROC_021_CASE_007");
            Assert.AreEqual(svr_viewer.Model.Test_Case_Status.NA_PCR_Exist, r.Status);


            System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(mc21.svr_viewer.ViewModel.Main_ViewModel));
            TextWriter tw = new StreamWriter("blend_data_2.xml");

            ser.Serialize(tw, vm);
            tw.Close();
        }
Exemplo n.º 40
0
        protected virtual System.Xml.Serialization.XmlSerializer GetSerializer <T>()
        {
            var serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));

            return(serializer);
        }
Exemplo n.º 41
0
        public void Deserialize(string samlResponse)
        {
            ResponseType response = new ResponseType();

            try
            {
                using (TextReader sr = new StringReader(samlResponse))
                {
                    var serializer = new System.Xml.Serialization.XmlSerializer(typeof(ResponseType));
                    response = (ResponseType)serializer.Deserialize(sr);

                    this.Version = response.Version;
                    this.UUID    = response.ID;
                    this.SPUID   = response.InResponseTo;
                    this.Issuer  = response.Issuer.Value;

                    switch (response.Status.StatusCode.Value)
                    {
                    case "urn:oasis:names:tc:SAML:2.0:status:Success":
                        this.RequestStatus = SamlRequestStatus.Success;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:Requester":
                        this.RequestStatus = SamlRequestStatus.RequesterError;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:Responder":
                        this.RequestStatus = SamlRequestStatus.ResponderError;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:VersionMismatch":
                        this.RequestStatus = SamlRequestStatus.VersionMismatchError;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:AuthnFailed":
                        this.RequestStatus = SamlRequestStatus.AuthnFailed;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:InvalidAttrNameOrValue":
                        this.RequestStatus = SamlRequestStatus.InvalidAttrNameOrValue;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:InvalidNameIDPolicy":
                        this.RequestStatus = SamlRequestStatus.InvalidNameIDPolicy;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:NoAuthnContext":
                        this.RequestStatus = SamlRequestStatus.NoAuthnContext;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:NoAvailableIDP":
                        this.RequestStatus = SamlRequestStatus.NoAvailableIDP;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:NoPassive":
                        this.RequestStatus = SamlRequestStatus.NoPassive;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:NoSupportedIDP":
                        this.RequestStatus = SamlRequestStatus.NoSupportedIDP;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:PartialLogout":
                        this.RequestStatus = SamlRequestStatus.PartialLogout;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:ProxyCountExceeded":
                        this.RequestStatus = SamlRequestStatus.ProxyCountExceeded;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:RequestDenied":
                        this.RequestStatus = SamlRequestStatus.RequestDenied;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:RequestUnsupported":
                        this.RequestStatus = SamlRequestStatus.RequestUnsupported;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:RequestVersionDeprecated":
                        this.RequestStatus = SamlRequestStatus.RequestVersionDeprecated;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:RequestVersionTooHigh":
                        this.RequestStatus = SamlRequestStatus.RequestVersionTooHigh;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:RequestVersionTooLow":
                        this.RequestStatus = SamlRequestStatus.RequestVersionTooLow;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:ResourceNotRecognized":
                        this.RequestStatus = SamlRequestStatus.ResourceNotRecognized;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:TooManyResponses":
                        this.RequestStatus = SamlRequestStatus.TooManyResponses;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:UnknownAttrProfile":
                        this.RequestStatus = SamlRequestStatus.UnknownAttrProfile;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:UnknownPrincipal":
                        this.RequestStatus = SamlRequestStatus.UnknownPrincipal;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:UnsupportedBinding":
                        this.RequestStatus = SamlRequestStatus.UnsupportedBinding;
                        break;

                    default:
                        this.RequestStatus = SamlRequestStatus.GenericError;
                        break;
                    }

                    if (this.RequestStatus == SamlRequestStatus.Success)
                    {
                        foreach (var item in response.Items)
                        {
                            if (item.GetType() == typeof(AssertionType))
                            {
                                AssertionType ass = (AssertionType)item;
                                this.SessionIdExpireDate = (ass.Conditions.NotOnOrAfter != null) ? ass.Conditions.NotOnOrAfter : DateTime.Now.AddMinutes(20);

                                foreach (var subitem in ass.Subject.Items)
                                {
                                    if (subitem.GetType() == typeof(NameIDType))
                                    {
                                        NameIDType nameId = (NameIDType)subitem;
                                        this.SubjectNameId = nameId.Value; //.Replace("SPID-","");
                                    }
                                }

                                foreach (var assItem in ass.Items)
                                {
                                    if (assItem.GetType() == typeof(AuthnStatementType))
                                    {
                                        AuthnStatementType authnStatement = (AuthnStatementType)assItem;
                                        this.SessionId           = authnStatement.SessionIndex;
                                        this.SessionIdExpireDate = (authnStatement.SessionNotOnOrAfterSpecified) ? authnStatement.SessionNotOnOrAfter : this.SessionIdExpireDate;
                                    }

                                    if (assItem.GetType() == typeof(AttributeStatementType))
                                    {
                                        AttributeStatementType statement = (AttributeStatementType)assItem;

                                        foreach (AttributeType attribute in statement.Items)
                                        {
                                            switch (attribute.Name)
                                            {
                                            case "spidCode":
                                                this.User.SpidCode = attribute.AttributeValue[0].ToString();
                                                break;

                                            case "name":
                                                this.User.Name = attribute.AttributeValue[0].ToString();
                                                break;

                                            case "familyName":
                                                this.User.FamilyName = attribute.AttributeValue[0].ToString();
                                                break;

                                            case "gender":
                                                this.User.Gender = attribute.AttributeValue[0].ToString();
                                                break;

                                            case "ivaCode":
                                                this.User.IvaCode = attribute.AttributeValue[0].ToString();
                                                break;

                                            case "companyName":
                                                this.User.CompanyName = attribute.AttributeValue[0].ToString();
                                                break;

                                            case "mobilePhone":
                                                this.User.MobilePhone = attribute.AttributeValue[0].ToString();
                                                break;

                                            case "address":
                                                this.User.Address = attribute.AttributeValue[0].ToString();
                                                break;

                                            case "fiscalNumber":
                                                this.User.FiscalNumber = attribute.AttributeValue[0].ToString();
                                                break;

                                            case "dateOfBirth":
                                                this.User.DateOfBirth = attribute.AttributeValue[0].ToString();
                                                break;

                                            case "placeOfBirth":
                                                this.User.PlaceOfBirth = attribute.AttributeValue[0].ToString();
                                                break;

                                            case "countyOfBirth":
                                                this.User.CountyOfBirth = attribute.AttributeValue[0].ToString();
                                                break;

                                            case "idCard":
                                                this.User.IdCard = attribute.AttributeValue[0].ToString();
                                                break;

                                            case "registeredOffice":
                                                this.User.RegisteredOffice = attribute.AttributeValue[0].ToString();
                                                break;

                                            case "email":
                                                this.User.Email = attribute.AttributeValue[0].ToString();
                                                break;

                                            case "expirationDate":
                                                this.User.ExpirationDate = attribute.AttributeValue[0].ToString();
                                                break;

                                            case "digitalAddress":
                                                this.User.DigitalAddress = attribute.AttributeValue[0].ToString();
                                                break;

                                            default:
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //TODO Log
                throw ex;
            }
        }
Exemplo n.º 42
0
        public void WriteXml(System.Xml.XmlWriter writer, FeedType feedType)
        {
            writer.WriteStartElement("entry", Namespaces.atomNamespace);
            // id
            writer.WriteElementString("id", Namespaces.atomNamespace, this.Id);
            // title
            writer.WriteElementString("title", Namespaces.atomNamespace, this.Title);

            // uuid
            if (this.IsUuidSet)
            {
                writer.WriteElementString("uuid", Namespaces.syncNamespace, this.Uuid.ToString());
            }

            foreach (SyncFeedEntryLink link in this.SyncLinks)
            {
                writer.WriteStartElement("link", Namespaces.atomNamespace);
                if (!String.IsNullOrEmpty(link.LinkRel))
                {
                    writer.WriteAttributeString("rel", link.LinkRel);
                }
                if (!String.IsNullOrEmpty(link.LinkType))
                {
                    writer.WriteAttributeString("type", link.LinkType);
                }
                if (!String.IsNullOrEmpty(link.Href))
                {
                    writer.WriteAttributeString("href", link.Href);
                }
                if (!String.IsNullOrEmpty(link.Title))
                {
                    writer.WriteAttributeString("title", link.Title);
                }
                if (!String.IsNullOrEmpty(link.PayloadPath))
                {
                    writer.WriteAttributeString(Namespaces.sdataPrefix, "payloadPath", Namespaces.sdataNamespace, link.PayloadPath);
                }
                if (!String.IsNullOrEmpty(link.Uuid))
                {
                    writer.WriteAttributeString(Namespaces.syncPrefix, "uuid", Namespaces.syncNamespace, link.Uuid);
                }
                writer.WriteEndElement();
            }

            switch (feedType)
            {
            case FeedType.Resource:
                break;

            case FeedType.SyncSource:
                //<!-- Per-Resource Synchronization State -->
                System.Xml.Serialization.XmlSerializer syncStateSerializer = new System.Xml.Serialization.XmlSerializer(typeof(SyncState));
                syncStateSerializer.Serialize(writer, this.SyncState);
                if (!String.IsNullOrEmpty(this.HttpMethod))
                {
                    writer.WriteElementString("httpMethod", Namespaces.sdataHttpNamespace, this.HttpMethod);
                }
                break;

            case FeedType.SyncTarget:
                writer.WriteElementString("httpStatus", Namespaces.sdataHttpNamespace, Convert.ToInt32(this.HttpStatusCode).ToString());
                writer.WriteElementString("httpMessage", Namespaces.sdataHttpNamespace, this.HttpMessage);
                writer.WriteElementString("location", Namespaces.sdataHttpNamespace, this.HttpLocation);
                writer.WriteElementString("httpMethod", Namespaces.sdataHttpNamespace, this.HttpMethod);

                break;

            case FeedType.Linked:
            case FeedType.LinkedSingle:
                System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(LinkedElement));
                serializer.Serialize(writer, this.Linked);

                break;
            }
            // Content ??
            // links  ??

            if (null != this.HttpETag)
            {
                writer.WriteElementString("etag", Namespaces.sdataHttpNamespace, this.HttpETag);
            }

            //<!-- XML payload -->
            if (this.Payload != null)
            {
                System.Xml.Serialization.XmlSerializer serializer;
                //if (this.Payload is TradingAccountPayload)
                serializer = new System.Xml.Serialization.XmlSerializer(this.Payload.GetType());
                //else
                //serializer = new System.Xml.Serialization.XmlSerializer(typeof(PayloadBase));
                serializer.Serialize(writer, this.Payload);
            }
            writer.WriteEndElement();
        }
Exemplo n.º 43
0
        private Object Deserialiase(Type aType, Stream aStream)
        {
            XmlSerializer xSerializer = new System.Xml.Serialization.XmlSerializer(aType);

            return(xSerializer.Deserialize(aStream));
        }
Exemplo n.º 44
0
        public void ProcessRequest(MIGClientRequest request, MIGInterfaceCommand migcmd)
        {
            string streamcontent = "";

            //
            _hg.ExecuteAutomationRequest(migcmd);
            //
            if (migcmd.command.StartsWith("Macro."))
            {
                switch (migcmd.command)
                {
                case "Macro.Record":
                    _hg.ProgramEngine.MacroRecorder.RecordingEnable();
                    break;

                case "Macro.Save":
                    ProgramBlock pb = _hg.ProgramEngine.MacroRecorder.SaveMacro(migcmd.GetOption(1));
                    migcmd.response = pb.Address.ToString();
                    break;

                case "Macro.Discard":
                    _hg.ProgramEngine.MacroRecorder.RecordingDisable();
                    break;

                case "Macro.SetDelay":
                    switch (migcmd.GetOption(0).ToLower())
                    {
                    case "none":
                        _hg.ProgramEngine.MacroRecorder.DelayType = MacroDelayType.None;
                        break;

                    case "mimic":
                        _hg.ProgramEngine.MacroRecorder.DelayType = MacroDelayType.Mimic;
                        break;

                    case "fixed":
                        double secs = double.Parse(migcmd.GetOption(1), System.Globalization.CultureInfo.InvariantCulture);
                        _hg.ProgramEngine.MacroRecorder.DelayType    = MacroDelayType.Fixed;
                        _hg.ProgramEngine.MacroRecorder.DelaySeconds = secs;
                        break;
                    }
                    break;

                case "Macro.GetDelay":
                    migcmd.response = "[{ DelayType : '" + _hg.ProgramEngine.MacroRecorder.DelayType + "', DelayOptions : '" + _hg.ProgramEngine.MacroRecorder.DelaySeconds + "' }]";
                    break;
                }
            }
            else if (migcmd.command.StartsWith("Scheduling."))
            {
                switch (migcmd.command)
                {
                case "Scheduling.Add":
                case "Scheduling.Update":
                    SchedulerItem item = _hg.ProgramEngine.SchedulerService.AddOrUpdate(migcmd.GetOption(0), migcmd.GetOption(1).Replace("|", "/"));
                    item.ProgramId = migcmd.GetOption(2);
                    _hg.UpdateSchedulerDatabase();
                    break;

                case "Scheduling.Delete":
                    _hg.ProgramEngine.SchedulerService.Remove(migcmd.GetOption(0));
                    _hg.UpdateSchedulerDatabase();
                    break;

                case "Scheduling.Enable":
                    _hg.ProgramEngine.SchedulerService.Enable(migcmd.GetOption(0));
                    _hg.UpdateSchedulerDatabase();
                    break;

                case "Scheduling.Disable":
                    _hg.ProgramEngine.SchedulerService.Disable(migcmd.GetOption(0));
                    _hg.UpdateSchedulerDatabase();
                    break;

                case "Scheduling.Get":
                    migcmd.response = JsonConvert.SerializeObject(_hg.ProgramEngine.SchedulerService.Get(migcmd.GetOption(0)));
                    break;

                case "Scheduling.List":
                    migcmd.response = JsonConvert.SerializeObject(_hg.ProgramEngine.SchedulerService.Items);
                    break;
                }
            }
            else if (migcmd.command.StartsWith("Programs."))
            {
                if (migcmd.command != "Programs.Import")
                {
                    streamcontent = new StreamReader(request.InputStream).ReadToEnd();
                }
                //
                ProgramBlock cp = null;
                //
                switch (migcmd.command)
                {
                case "Programs.Import":
                    string archivename = "homegenie_program_import.hgx";
                    if (File.Exists(archivename))
                    {
                        File.Delete(archivename);
                    }
                    //
                    Encoding enc      = (request.Context as HttpListenerContext).Request.ContentEncoding;
                    string   boundary = MIG.Gateways.WebServiceUtility.GetBoundary((request.Context as HttpListenerContext).Request.ContentType);
                    MIG.Gateways.WebServiceUtility.SaveFile(enc, boundary, request.InputStream, archivename);
                    //
                    XmlSerializer mserializer  = new XmlSerializer(typeof(ProgramBlock));
                    StreamReader  mreader      = new StreamReader(archivename);
                    ProgramBlock  programblock = (ProgramBlock)mserializer.Deserialize(mreader);
                    mreader.Close();
                    //
                    programblock.Address = _hg.ProgramEngine.GeneratePid();
                    programblock.Group   = migcmd.GetOption(0);
                    _hg.ProgramEngine.ProgramAdd(programblock);
                    //
                    //TODO: move program compilation into an method of ProgramEngine and also apply to Programs.Update
                    programblock.IsEnabled      = false;
                    programblock.ScriptErrors   = "";
                    programblock.ScriptAssembly = null;
                    //
                    // DISABLED IN FLAVOUR OF USER ASSISTED ENABLING, to prevent malicious scripts to start automatically
                    // in case of c# script type, we have to recompile it

                    /*
                     * if (programblock.Type.ToLower() == "csharp" && programblock.IsEnabled)
                     * {
                     *  System.CodeDom.Compiler.CompilerResults res = _mastercontrolprogram.CompileScript(programblock);
                     *  //
                     *  if (res.Errors.Count == 0)
                     *  {
                     *      programblock.ScriptAssembly = res.CompiledAssembly;
                     *  }
                     *  else
                     *  {
                     *      int sourcelines = programblock.ScriptSource.Split('\n').Length;
                     *      foreach (System.CodeDom.Compiler.CompilerError ce in res.Errors)
                     *      {
                     *          //if (!ce.IsWarning)
                     *          {
                     *              int errline = (ce.Line - 16);
                     *              string blocktype = "Code";
                     *              if (errline >= sourcelines + 7)
                     *              {
                     *                  errline -= (sourcelines + 7);
                     *                  blocktype = "Condition";
                     *              }
                     *              string errmsg = "Line " + errline + ", Column " + ce.Column + " " + ce.ErrorText + " (" + ce.ErrorNumber + ")";
                     *              programblock.ScriptErrors += errmsg + " (" + blocktype + ")" + "\n";
                     *          }
                     *      }
                     *  }
                     * }
                     * //
                     * cmd.response = programblock.ScriptErrors;
                     */
                    //
                    _hg.UpdateProgramsDatabase();
                    //cmd.response = JsonHelper.GetSimpleResponse(programblock.Address);
                    migcmd.response = programblock.Address.ToString();
                    break;

                case "Programs.Export":
                    cp = _hg.ProgramEngine.Programs.Find(p => p.Address == int.Parse(migcmd.GetOption(0)));
                    System.Xml.XmlWriterSettings ws = new System.Xml.XmlWriterSettings();
                    ws.Indent = true;
                    System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(ProgramBlock));
                    StringBuilder        sb  = new StringBuilder();
                    System.Xml.XmlWriter wri = System.Xml.XmlWriter.Create(sb, ws);
                    x.Serialize(wri, cp);
                    wri.Close();
                    migcmd.response = sb.ToString();
                    //
                    (request.Context as HttpListenerContext).Response.AddHeader("Content-Disposition", "attachment; filename=\"" + cp.Address + "-" + cp.Name.Replace(" ", "_") + ".hgx\"");
                    break;

                case "Programs.List":
                    List <ProgramBlock> prgs = new List <ProgramBlock>(_hg.ProgramEngine.Programs);
                    prgs.Sort(delegate(ProgramBlock p1, ProgramBlock p2)
                    {
                        string c1 = p1.Name + " " + p1.Address;
                        string c2 = p2.Name + " " + p2.Address;
                        return(c1.CompareTo(c2));
                    });
                    migcmd.response = JsonConvert.SerializeObject(prgs);
                    break;

                case "Programs.Add":
                    ProgramBlock pb = new ProgramBlock()
                    {
                        Group = migcmd.GetOption(0), Name = streamcontent, Type = "Wizard", ScriptCondition = "// A \"return true;\" statement at any point of this code block, will cause the program to run.\n// For manually activated program, just leave a \"return false\" statement here.\n\nreturn false;\n"
                    };
                    pb.Address = _hg.ProgramEngine.GeneratePid();
                    _hg.ProgramEngine.ProgramAdd(pb);
                    _hg.UpdateProgramsDatabase();
                    migcmd.response = JsonHelper.GetSimpleResponse(pb.Address.ToString());
                    break;

                case "Programs.Delete":
                    cp = _hg.ProgramEngine.Programs.Find(p => p.Address == int.Parse(migcmd.GetOption(0)));
                    if (cp != null)
                    {
                        //TODO: remove groups associations as well
                        cp.IsEnabled = false;
                        _hg.ProgramEngine.ProgramRemove(cp);
                        _hg.UpdateProgramsDatabase();
                        // remove associated module entry
                        _hg.Modules.RemoveAll(m => m.Domain == Domains.HomeAutomation_HomeGenie_Automation && m.Address == cp.Address.ToString());
                        _hg.UpdateModulesDatabase();
                    }
                    break;

                case "Programs.Compile":
                case "Programs.Update":
                    programblock = JsonConvert.DeserializeObject <ProgramBlock>(streamcontent);
                    cp           = _hg.ProgramEngine.Programs.Find(p => p.Address == programblock.Address);
                    //
                    if (cp == null)
                    {
                        programblock.Address = _hg.ProgramEngine.GeneratePid();
                        _hg.ProgramEngine.ProgramAdd(programblock);
                    }
                    else
                    {
                        if (cp.Type.ToLower() != programblock.Type.ToLower())
                        {
                            cp.ScriptAssembly = null;     // dispose assembly and interrupt current task
                        }
                        cp.Type            = programblock.Type;
                        cp.Group           = programblock.Group;
                        cp.Name            = programblock.Name;
                        cp.Description     = programblock.Description;
                        cp.IsEnabled       = programblock.IsEnabled;
                        cp.ScriptCondition = programblock.ScriptCondition;
                        cp.ScriptSource    = programblock.ScriptSource;
                        cp.Commands        = programblock.Commands;
                        cp.Conditions      = programblock.Conditions;
                        cp.ConditionType   = programblock.ConditionType;
                        // reset last condition evaluation status
                        cp.LastConditionEvaluationResult = false;
                    }

                    if (migcmd.command == "Programs.Compile" && cp.Type.ToLower() == "csharp") // && programblock.IsEnabled)
                    {
                        cp.ScriptAssembly = null;                                              // dispose assembly and interrupt current task
                        cp.IsEnabled      = false;
                        cp.ScriptErrors   = "";
                        //
                        System.CodeDom.Compiler.CompilerResults res = _hg.ProgramEngine.CompileScript(cp);
                        //
                        if (res.Errors.Count == 0)
                        {
                            cp.ScriptAssembly = res.CompiledAssembly;
                        }
                        else
                        {
                            int sourcelines = cp.ScriptSource.Split('\n').Length;
                            foreach (System.CodeDom.Compiler.CompilerError ce in res.Errors)
                            {
                                //if (!ce.IsWarning)
                                {
                                    int    errline   = (ce.Line - 16);
                                    string blocktype = "Code";
                                    if (errline >= sourcelines + 7)
                                    {
                                        errline  -= (sourcelines + 7);
                                        blocktype = "Condition";
                                    }
                                    string errmsg = "Line " + errline + ", Column " + ce.Column + " " + ce.ErrorText + " (" + ce.ErrorNumber + ")";
                                    cp.ScriptErrors += errmsg + " (" + blocktype + ")" + "\n";
                                }
                            }
                        }
                        //
                        cp.IsEnabled = programblock.IsEnabled;
                        //
                        migcmd.response = cp.ScriptErrors;
                    }

                    _hg.UpdateProgramsDatabase();
                    //
                    _hg._modules_refresh_virtualmods();
                    _hg._modules_sort();
                    break;

                case "Programs.Run":
                    cp = _hg.ProgramEngine.Programs.Find(p => p.Address == int.Parse(migcmd.GetOption(0)));
                    if (cp != null)
                    {
                        _hg.ProgramEngine.Run(cp, migcmd.GetOption(1));
                    }
                    break;

                case "Programs.Break":
                    cp = _hg.ProgramEngine.Programs.Find(p => p.Address == int.Parse(migcmd.GetOption(0)));
                    if (cp != null)
                    {
                        cp.Stop();
                        _hg.UpdateProgramsDatabase();
                    }
                    break;

                case "Programs.Enable":
                    cp = _hg.ProgramEngine.Programs.Find(p => p.Address == int.Parse(migcmd.GetOption(0)));
                    if (cp != null)
                    {
                        cp.IsEnabled = true;
                        _hg.UpdateProgramsDatabase();
                    }
                    break;

                case "Programs.Disable":
                    cp = _hg.ProgramEngine.Programs.Find(p => p.Address == int.Parse(migcmd.GetOption(0)));
                    if (cp != null)
                    {
                        cp.IsEnabled = false;
                        try
                        {
                            cp.Stop();
                        }
                        catch { }
                        _hg.UpdateProgramsDatabase();
                    }
                    break;
                }
            }
        }
Exemplo n.º 45
0
 public static EventDefQuick LoadEventData(System.IO.Stream filestream)
 {
     System.Xml.Serialization.XmlSerializer s = new System.Xml.Serialization.XmlSerializer(typeof(EventDefQuick));
     return(s.Deserialize(filestream) as EventDefQuick);
 }
Exemplo n.º 46
0
        static void Main(string[] args)
        {
            Program program;
            string  filePath = AppDomain.CurrentDomain.BaseDirectory + "values.txt";

            if (File.Exists(filePath))
            {
                System.Xml.Serialization.XmlSerializer xmlReader = new System.Xml.Serialization.XmlSerializer(typeof(Program));
                var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                program = (Program)xmlReader.Deserialize(fileStream);
                fileStream.Close();
            }
            else
            {
                program = new Program();
                System.IO.File.Create(filePath).Close();
                program.save(program);
            }
            Console.WriteLine("Todo App");
            while (true)
            {
                Console.WriteLine("Waiting for input...");
                string   input = Console.ReadLine();
                string[] words = input.Split(" ");
                try
                {
                    if (words[0].Equals("Add"))
                    {
                        try
                        {
                            string s = "";
                            for (int i = 1; i < words.Length; i++)
                            {
                                s += words[i] + " ";
                            }
                            program.add(s);
                        }
                        catch
                        {
                            Console.WriteLine("Please give a name of the todo-element.");
                        }
                    }
                    else if (words[0].Equals("Do"))
                    {
                        try
                        {
                            program.doTask(Int32.Parse(words[1]));
                        }
                        catch
                        {
                            Console.WriteLine("Please specify a number after 'Do'.");
                        }
                    }
                    else if (words[0].Equals("Print"))
                    {
                        program.print();
                    }
                    else
                    {
                        Console.WriteLine(words[0] + " is not recognised as an internal command.");
                    }
                }
                catch
                {
                    Console.WriteLine("Unknown command.");
                }
                program.save(program);
            }
        }
Exemplo n.º 47
0
        private void openObjFlowxmlToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog()
            {
                Title            = "Open ObjFlow.xml",
                InitialDirectory = @"C:\Users\User\Desktop",
                Filter           = "xml file|*.xml"
            };

            if (openFileDialog1.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            System.IO.FileStream fs1 = new FileStream(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);                                                  //ファイルを開く
            System.Xml.Serialization.XmlSerializer s1 = new System.Xml.Serialization.XmlSerializer(typeof(MK8_ObjFlow.xml_Reader.ObjFlow_Xml.ObjFlow_Read_ROOT)); //ObjFlow_ROOT.cs
            MK8_ObjFlow.xml_Reader.ObjFlow_Xml.ObjFlow_Read_ROOT BYAML_XML_Model = (MK8_ObjFlow.xml_Reader.ObjFlow_Xml.ObjFlow_Read_ROOT)s1.Deserialize(fs1);     //MK8_ObjFlow.xml_Reader.ObjFlow_Xml.ObjFlow_ROOTクラスの内容をデシリアライズ

            foreach (MK8_ObjFlow.xml_Reader.ObjFlow_Xml.Value_Array BYAML_XML_UMDL in BYAML_XML_Model.Value_Arrays)                                               //foreachで繰り返し要素のあるXMLを読み込む
            {
                //dataGridViewに表示
                dataGridView1.Rows.Add(BYAML_XML_UMDL.AiReact,
                                       BYAML_XML_UMDL.CalcCut,
                                       BYAML_XML_UMDL.Clip,
                                       BYAML_XML_UMDL.ClipRadius,
                                       BYAML_XML_UMDL.ColOffsetY,
                                       BYAML_XML_UMDL.ColShape,
                                       BYAML_XML_UMDL.DemoCameraCheck,
                                       BYAML_XML_UMDL.LightSetting,
                                       BYAML_XML_UMDL.Lod1,
                                       BYAML_XML_UMDL.Lod2,
                                       BYAML_XML_UMDL.Lod_NoDisp,
                                       BYAML_XML_UMDL.MgrId,
                                       BYAML_XML_UMDL.ModelDraw,
                                       BYAML_XML_UMDL.ModelEffNo,
                                       BYAML_XML_UMDL.MoveBeforeSync,
                                       BYAML_XML_UMDL.NotCreate,
                                       BYAML_XML_UMDL.ObjId,
                                       BYAML_XML_UMDL.Offset,
                                       BYAML_XML_UMDL.Origin,
                                       BYAML_XML_UMDL.PackunEat,
                                       BYAML_XML_UMDL.PathType,
                                       BYAML_XML_UMDL.PylonReact,
                                       BYAML_XML_UMDL.VR);

                dataGridView2.Rows.Add(BYAML_XML_UMDL.ColSize.X_Val,
                                       BYAML_XML_UMDL.ColSize.Y_Val,
                                       BYAML_XML_UMDL.ColSize.Z_Val,
                                       BYAML_XML_UMDL.Items.Item_Value_Ary[0].ItemVal,
                                       BYAML_XML_UMDL.Items.Item_Value_Ary[1].ItemVal,
                                       BYAML_XML_UMDL.Items.Item_Value_Ary[2].ItemVal,
                                       BYAML_XML_UMDL.Items.Item_Value_Ary[3].ItemVal,
                                       BYAML_XML_UMDL.Items.Item_Value_Ary[4].ItemVal,
                                       BYAML_XML_UMDL.Items.Item_Value_Ary[5].ItemVal,
                                       BYAML_XML_UMDL.Items.Item_Value_Ary[6].ItemVal,
                                       BYAML_XML_UMDL.Items.Item_Value_Ary[7].ItemVal,
                                       BYAML_XML_UMDL.Items.Item_Value_Ary[8].ItemVal,
                                       BYAML_XML_UMDL.Items.Item_Value_Ary[9].ItemVal,
                                       BYAML_XML_UMDL.Items.Item_Value_Ary[10].ItemVal,
                                       BYAML_XML_UMDL.Items.Item_Value_Ary[11].ItemVal,
                                       BYAML_XML_UMDL.Items.Item_Value_Ary[12].ItemVal,
                                       BYAML_XML_UMDL.ItemObjs.ItemObj_Value_Ary[0].ItemObjVal,
                                       BYAML_XML_UMDL.ItemObjs.ItemObj_Value_Ary[1].ItemObjVal,
                                       BYAML_XML_UMDL.ItemObjs.ItemObj_Value_Ary[2].ItemObjVal,
                                       BYAML_XML_UMDL.ItemObjs.ItemObj_Value_Ary[3].ItemObjVal,
                                       BYAML_XML_UMDL.ItemObjs.ItemObj_Value_Ary[4].ItemObjVal,
                                       BYAML_XML_UMDL.ItemObjs.ItemObj_Value_Ary[5].ItemObjVal,
                                       BYAML_XML_UMDL.ItemObjs.ItemObj_Value_Ary[6].ItemObjVal,
                                       BYAML_XML_UMDL.ItemObjs.ItemObj_Value_Ary[7].ItemObjVal,
                                       BYAML_XML_UMDL.ItemObjs.ItemObj_Value_Ary[8].ItemObjVal,
                                       BYAML_XML_UMDL.ItemObjs.ItemObj_Value_Ary[9].ItemObjVal,
                                       BYAML_XML_UMDL.ItemObjs.ItemObj_Value_Ary[10].ItemObjVal,
                                       BYAML_XML_UMDL.ItemObjs.ItemObj_Value_Ary[11].ItemObjVal,
                                       BYAML_XML_UMDL.ItemObjs.ItemObj_Value_Ary[12].ItemObjVal,
                                       BYAML_XML_UMDL.Karts.Kart_Value_Ary[0].KartVal,
                                       BYAML_XML_UMDL.Karts.Kart_Value_Ary[1].KartVal,
                                       BYAML_XML_UMDL.Karts.Kart_Value_Ary[2].KartVal,
                                       BYAML_XML_UMDL.Karts.Kart_Value_Ary[3].KartVal,
                                       BYAML_XML_UMDL.KartObjs.KartObj_Value_Ary[0].KartObjVal,
                                       BYAML_XML_UMDL.KartObjs.KartObj_Value_Ary[1].KartObjVal,
                                       BYAML_XML_UMDL.KartObjs.KartObj_Value_Ary[2].KartObjVal,
                                       BYAML_XML_UMDL.KartObjs.KartObj_Value_Ary[3].KartObjVal,
                                       BYAML_XML_UMDL.Label.Label_String,
                                       BYAML_XML_UMDL.ResNames.ResName_Value_Ary[0].ResNameStr);
            }
            fs1.Close();
        }
Exemplo n.º 48
0
 public void SaveEventData(System.IO.Stream filestream)
 {
     System.Xml.Serialization.XmlSerializer s = new System.Xml.Serialization.XmlSerializer(typeof(EventDefQuick));
     s.Serialize(filestream, this);
 }
Exemplo n.º 49
0
        public static Object Load(Object serializableObject, StringReader reader)
        {
            System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(serializableObject.GetType());

            return(xs.Deserialize(reader));
        }//StringReader
Exemplo n.º 50
0
        public void ProcessRequest(MigClientRequest request)
        {
            var          migCommand    = request.Command;
            string       streamContent = "";
            ProgramBlock currentProgram;
            ProgramBlock newProgram;
            string       sketchFile = "", sketchFolder = "";

            //
            homegenie.ExecuteAutomationRequest(migCommand);
            if (migCommand.Command.StartsWith("Macro."))
            {
                switch (migCommand.Command)
                {
                case "Macro.Record":
                    homegenie.ProgramManager.MacroRecorder.RecordingEnable();
                    break;

                case "Macro.Save":
                    newProgram           = homegenie.ProgramManager.MacroRecorder.SaveMacro(migCommand.GetOption(1));
                    request.ResponseData = newProgram.Address.ToString();
                    break;

                case "Macro.Discard":
                    homegenie.ProgramManager.MacroRecorder.RecordingDisable();
                    break;

                case "Macro.SetDelay":
                    switch (migCommand.GetOption(0).ToLower())
                    {
                    case "none":
                        homegenie.ProgramManager.MacroRecorder.DelayType = MacroDelayType.None;
                        break;

                    case "mimic":
                        homegenie.ProgramManager.MacroRecorder.DelayType = MacroDelayType.Mimic;
                        break;

                    case "fixed":
                        double secs = double.Parse(
                            migCommand.GetOption(1),
                            System.Globalization.CultureInfo.InvariantCulture
                            );
                        homegenie.ProgramManager.MacroRecorder.DelayType    = MacroDelayType.Fixed;
                        homegenie.ProgramManager.MacroRecorder.DelaySeconds = secs;
                        break;
                    }
                    break;

                case "Macro.GetDelay":
                    request.ResponseData = "{ \"DelayType\" : \"" + homegenie.ProgramManager.MacroRecorder.DelayType + "\", \"DelayOptions\" : \"" + homegenie.ProgramManager.MacroRecorder.DelaySeconds + "\" }";
                    break;
                }
            }
            else if (migCommand.Command.StartsWith("Scheduling."))
            {
                switch (migCommand.Command)
                {
                case "Scheduling.Add":
                case "Scheduling.Update":
                    var item = homegenie.ProgramManager.SchedulerService.AddOrUpdate(
                        migCommand.GetOption(0),
                        migCommand.GetOption(1).Replace(
                            "|",
                            "/"
                            )
                        );
                    item.ProgramId = migCommand.GetOption(2);
                    homegenie.UpdateSchedulerDatabase();
                    break;

                case "Scheduling.Delete":
                    homegenie.ProgramManager.SchedulerService.Remove(migCommand.GetOption(0));
                    homegenie.UpdateSchedulerDatabase();
                    break;

                case "Scheduling.Enable":
                    homegenie.ProgramManager.SchedulerService.Enable(migCommand.GetOption(0));
                    homegenie.UpdateSchedulerDatabase();
                    break;

                case "Scheduling.Disable":
                    homegenie.ProgramManager.SchedulerService.Disable(migCommand.GetOption(0));
                    homegenie.UpdateSchedulerDatabase();
                    break;

                case "Scheduling.Get":
                    request.ResponseData = homegenie.ProgramManager.SchedulerService.Get(migCommand.GetOption(0));
                    break;

                case "Scheduling.List":
                    homegenie.ProgramManager.SchedulerService.Items.Sort((SchedulerItem s1, SchedulerItem s2) =>
                    {
                        return(s1.Name.CompareTo(s2.Name));
                    });
                    request.ResponseData = homegenie.ProgramManager.SchedulerService.Items;
                    break;

                case "Scheduling.Describe":
                    var cronDescription = "";
                    try {
                        cronDescription = ExpressionDescriptor.GetDescription(migCommand.GetOption(0));
                        cronDescription = Char.ToLowerInvariant(cronDescription[0]) + cronDescription.Substring(1);
                    } catch { }
                    request.ResponseData = new ResponseText(cronDescription);
                    break;
                }
            }
            else if (migCommand.Command.StartsWith("Programs."))
            {
                if (migCommand.Command != "Programs.Import")
                {
                    streamContent = request.RequestText;
                }
                //
                switch (migCommand.Command)
                {
                case "Programs.Import":
                    string archiveName = "homegenie_program_import.hgx";
                    if (File.Exists(archiveName))
                    {
                        File.Delete(archiveName);
                    }
                    //
                    MIG.Gateways.WebServiceUtility.SaveFile(request.RequestData, archiveName);
                    //
                    int    newPid    = homegenie.ProgramManager.GeneratePid();
                    var    reader    = new StreamReader(archiveName);
                    char[] signature = new char[2];
                    reader.Read(signature, 0, 2);
                    reader.Close();
                    if (signature[0] == 'P' && signature[1] == 'K')
                    {
                        // Read and uncompress zip file content (arduino program bundle)
                        string zipFileName = archiveName.Replace(".hgx", ".zip");
                        if (File.Exists(zipFileName))
                        {
                            File.Delete(zipFileName);
                        }
                        File.Move(archiveName, zipFileName);
                        string destFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Utility.GetTmpFolder(), "import");
                        if (Directory.Exists(destFolder))
                        {
                            Directory.Delete(destFolder, true);
                        }
                        Utility.UncompressZip(zipFileName, destFolder);
                        string bundleFolder = Path.Combine("programs", "arduino", newPid.ToString());
                        if (Directory.Exists(bundleFolder))
                        {
                            Directory.Delete(bundleFolder, true);
                        }
                        if (!Directory.Exists(Path.Combine("programs", "arduino")))
                        {
                            Directory.CreateDirectory(Path.Combine("programs", "arduino"));
                        }
                        Directory.Move(Path.Combine(destFolder, "src"), bundleFolder);
                        reader = new StreamReader(Path.Combine(destFolder, "program.hgx"));
                    }
                    else
                    {
                        reader = new StreamReader(archiveName);
                    }
                    var serializer = new XmlSerializer(typeof(ProgramBlock));
                    newProgram = (ProgramBlock)serializer.Deserialize(reader);
                    reader.Close();
                    //
                    newProgram.Address = newPid;
                    newProgram.Group   = migCommand.GetOption(0);
                    homegenie.ProgramManager.ProgramAdd(newProgram);
                    //
                    newProgram.IsEnabled    = false;
                    newProgram.ScriptErrors = "";
                    newProgram.Engine.SetHost(homegenie);
                    //
                    if (newProgram.Type.ToLower() != "arduino")
                    {
                        homegenie.ProgramManager.CompileScript(newProgram);
                    }
                    //
                    homegenie.UpdateProgramsDatabase();
                    //migCommand.response = JsonHelper.GetSimpleResponse(programblock.Address);
                    request.ResponseData = newProgram.Address.ToString();
                    break;

                case "Programs.Export":
                    currentProgram = homegenie.ProgramManager.Programs.Find(p => p.Address == int.Parse(migCommand.GetOption(0)));
                    string filename = currentProgram.Address + "-" + currentProgram.Name.Replace(" ", "_");
                    //
                    var writerSettings = new System.Xml.XmlWriterSettings();
                    writerSettings.Indent = true;
                    var programSerializer = new System.Xml.Serialization.XmlSerializer(typeof(ProgramBlock));
                    var builder           = new StringBuilder();
                    var writer            = System.Xml.XmlWriter.Create(builder, writerSettings);
                    programSerializer.Serialize(writer, currentProgram);
                    writer.Close();
                    //
                    if (currentProgram.Type.ToLower() == "arduino")
                    {
                        string arduinoBundle = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                                            Utility.GetTmpFolder(),
                                                            "export",
                                                            filename + ".zip");
                        if (File.Exists(arduinoBundle))
                        {
                            File.Delete(arduinoBundle);
                        }
                        else if (!Directory.Exists(Path.GetDirectoryName(arduinoBundle)))
                        {
                            Directory.CreateDirectory(Path.GetDirectoryName(arduinoBundle));
                        }
                        string mainProgramFile = Path.Combine(Path.GetDirectoryName(arduinoBundle), "program.hgx");
                        File.WriteAllText(
                            mainProgramFile,
                            builder.ToString()
                            );
                        Utility.AddFileToZip(arduinoBundle, mainProgramFile, "program.hgx");
                        sketchFolder = Path.Combine("programs", "arduino", currentProgram.Address.ToString());
                        foreach (string f in Directory.GetFiles(sketchFolder))
                        {
                            if (!Path.GetFileName(f).StartsWith("sketch_"))
                            {
                                Utility.AddFileToZip(
                                    arduinoBundle,
                                    Path.Combine(sketchFolder, Path.GetFileName(f)),
                                    Path.Combine(
                                        "src",
                                        Path.GetFileName(f)
                                        )
                                    );
                            }
                        }
                        //
                        byte[] bundleData = File.ReadAllBytes(arduinoBundle);
                        (request.Context.Data as HttpListenerContext).Response.AddHeader(
                            "Content-Disposition",
                            "attachment; filename=\"" + filename + ".zip\""
                            );
                        (request.Context.Data as HttpListenerContext).Response.OutputStream.Write(bundleData, 0, bundleData.Length);
                    }
                    else
                    {
                        (request.Context.Data as HttpListenerContext).Response.AddHeader(
                            "Content-Disposition",
                            "attachment; filename=\"" + filename + ".hgx\""
                            );
                        request.ResponseData = builder.ToString();
                    }
                    break;

                case "Programs.List":
                    var programList = new List <ProgramBlock>(homegenie.ProgramManager.Programs);
                    programList.Sort(delegate(ProgramBlock p1, ProgramBlock p2)
                    {
                        string c1 = p1.Name + " " + p1.Address;
                        string c2 = p2.Name + " " + p2.Address;
                        return(c1.CompareTo(c2));
                    });
                    request.ResponseData = programList;
                    break;

                case "Programs.Add":
                    newProgram = new ProgramBlock()
                    {
                        Group = migCommand.GetOption(0),
                        Name  = streamContent,
                        Type  = "Wizard"
                    };
                    newProgram.Address = homegenie.ProgramManager.GeneratePid();
                    homegenie.ProgramManager.ProgramAdd(newProgram);
                    homegenie.UpdateProgramsDatabase();
                    request.ResponseData = new ResponseText(newProgram.Address.ToString());
                    break;

                case "Programs.Delete":
                    currentProgram = homegenie.ProgramManager.Programs.Find(p => p.Address == int.Parse(migCommand.GetOption(0)));
                    if (currentProgram != null)
                    {
                        //TODO: remove groups associations as well
                        homegenie.ProgramManager.ProgramRemove(currentProgram);
                        homegenie.UpdateProgramsDatabase();
                        // remove associated module entry
                        homegenie.Modules.RemoveAll(m => m.Domain == Domains.HomeAutomation_HomeGenie_Automation && m.Address == currentProgram.Address.ToString());
                        homegenie.UpdateModulesDatabase();
                    }
                    break;

                case "Programs.Compile":
                case "Programs.Update":
                    newProgram     = JsonConvert.DeserializeObject <ProgramBlock>(streamContent);
                    currentProgram = homegenie.ProgramManager.Programs.Find(p => p.Address == newProgram.Address);
                    //
                    if (currentProgram == null)
                    {
                        newProgram.Address = homegenie.ProgramManager.GeneratePid();
                        homegenie.ProgramManager.ProgramAdd(newProgram);
                    }
                    else
                    {
                        bool typeChanged = (currentProgram.Type.ToLower() != newProgram.Type.ToLower());
                        currentProgram.Type        = newProgram.Type;
                        currentProgram.Group       = newProgram.Group;
                        currentProgram.Name        = newProgram.Name;
                        currentProgram.Description = newProgram.Description;
                        if (typeChanged)
                        {
                            currentProgram.Engine.SetHost(homegenie);
                        }
                        currentProgram.IsEnabled       = newProgram.IsEnabled;
                        currentProgram.ScriptCondition = newProgram.ScriptCondition;
                        currentProgram.ScriptSource    = newProgram.ScriptSource;
                        currentProgram.Commands        = newProgram.Commands;
                        currentProgram.Conditions      = newProgram.Conditions;
                        currentProgram.ConditionType   = newProgram.ConditionType;
                        // reset last condition evaluation status
                        currentProgram.LastConditionEvaluationResult = false;
                    }
                    //
                    if (migCommand.Command == "Programs.Compile")
                    {
                        // reset previous error status
                        currentProgram.IsEnabled = false;
                        currentProgram.Engine.Stop();
                        currentProgram.ScriptErrors = "";
                        //
                        List <ProgramError> errors = homegenie.ProgramManager.CompileScript(currentProgram);
                        //
                        currentProgram.IsEnabled    = newProgram.IsEnabled && errors.Count == 0;
                        currentProgram.ScriptErrors = JsonConvert.SerializeObject(errors);
                        request.ResponseData        = currentProgram.ScriptErrors;
                    }
                    //
                    homegenie.UpdateProgramsDatabase();
                    //
                    homegenie.modules_RefreshPrograms();
                    homegenie.modules_RefreshVirtualModules();
                    homegenie.modules_Sort();
                    break;

                case "Programs.Arduino.FileLoad":
                    sketchFolder = Path.GetDirectoryName(ArduinoAppFactory.GetSketchFile(migCommand.GetOption(0)));
                    sketchFile   = migCommand.GetOption(1);
                    if (sketchFile == "main")
                    {
                        // "main" is a special keyword to indicate the main program sketch file
                        sketchFile = ArduinoAppFactory.GetSketchFile(migCommand.GetOption(0));
                    }
                    sketchFile           = Path.Combine(sketchFolder, Path.GetFileName(sketchFile));
                    request.ResponseData = new ResponseText(File.ReadAllText(sketchFile));
                    break;

                case "Programs.Arduino.FileSave":
                    sketchFolder = Path.GetDirectoryName(ArduinoAppFactory.GetSketchFile(migCommand.GetOption(0)));
                    sketchFile   = Path.Combine(sketchFolder, Path.GetFileName(migCommand.GetOption(1)));
                    File.WriteAllText(sketchFile, streamContent);
                    break;

                case "Programs.Arduino.FileAdd":
                    sketchFolder = Path.GetDirectoryName(ArduinoAppFactory.GetSketchFile(migCommand.GetOption(0)));
                    if (!Directory.Exists(sketchFolder))
                    {
                        Directory.CreateDirectory(sketchFolder);
                    }
                    sketchFile = Path.Combine(sketchFolder, Path.GetFileName(migCommand.GetOption(1)));
                    if (File.Exists(sketchFile))
                    {
                        request.ResponseData = new ResponseText("EXISTS");
                    }
                    else if (!ArduinoAppFactory.IsValidProjectFile(sketchFile))
                    {
                        request.ResponseData = new ResponseText("INVALID_NAME");
                    }
                    else
                    {
                        StreamWriter sw = File.CreateText(sketchFile);
                        sw.Close();
                        sw.Dispose();
                        sw = null;
                        request.ResponseData = new ResponseText("OK");
                    }
                    break;

                case "Programs.Arduino.FileDelete":
                    sketchFolder = Path.GetDirectoryName(ArduinoAppFactory.GetSketchFile(migCommand.GetOption(0)));
                    sketchFile   = Path.Combine(sketchFolder, Path.GetFileName(migCommand.GetOption(1)));
                    if (!File.Exists(sketchFile))
                    {
                        request.ResponseData = new ResponseText("NOT_FOUND");
                    }
                    else
                    {
                        File.Delete(sketchFile);
                        request.ResponseData = new ResponseText("OK");
                    }
                    break;

                case "Programs.Arduino.FileList":
                    sketchFolder = Path.GetDirectoryName(ArduinoAppFactory.GetSketchFile(migCommand.GetOption(0)));
                    List <string> files = new List <string>();
                    foreach (string f in Directory.GetFiles(sketchFolder))
                    {
                        if (ArduinoAppFactory.IsValidProjectFile(f))
                        {
                            files.Add(Path.GetFileName(f));
                        }
                    }
                    request.ResponseData = files;
                    break;

                case "Programs.Run":
                    currentProgram = homegenie.ProgramManager.Programs.Find(p => p.Address == int.Parse(migCommand.GetOption(0)));
                    if (currentProgram != null)
                    {
                        // clear any runtime errors before running
                        currentProgram.ScriptErrors = "";
                        homegenie.ProgramManager.RaiseProgramModuleEvent(
                            currentProgram,
                            Properties.RuntimeError,
                            ""
                            );
                        currentProgram.IsEnabled = true;
                        ProgramRun(migCommand.GetOption(0), migCommand.GetOption(1));
                    }
                    break;

                case "Programs.Toggle":
                    currentProgram = ProgramToggle(migCommand.GetOption(0), migCommand.GetOption(1));
                    break;

                case "Programs.Break":
                    currentProgram = ProgramBreak(migCommand.GetOption(0));
                    break;

                case "Programs.Restart":
                    currentProgram = homegenie.ProgramManager.Programs.Find(p => p.Address == int.Parse(migCommand.GetOption(0)));
                    if (currentProgram != null)
                    {
                        currentProgram.IsEnabled = false;
                        try
                        {
                            currentProgram.Engine.Stop();
                        }
                        catch
                        {
                        }
                        currentProgram.IsEnabled = true;
                        homegenie.UpdateProgramsDatabase();
                    }
                    break;

                case "Programs.Enable":
                    currentProgram = homegenie.ProgramManager.Programs.Find(p => p.Address == int.Parse(migCommand.GetOption(0)));
                    if (currentProgram != null)
                    {
                        currentProgram.IsEnabled = true;
                        homegenie.UpdateProgramsDatabase();
                    }
                    break;

                case "Programs.Disable":
                    currentProgram = homegenie.ProgramManager.Programs.Find(p => p.Address == int.Parse(migCommand.GetOption(0)));
                    if (currentProgram != null)
                    {
                        currentProgram.IsEnabled = false;
                        try
                        {
                            currentProgram.Engine.Stop();
                        }
                        catch
                        {
                        }
                        homegenie.UpdateProgramsDatabase();
                    }
                    break;
                }
            }
        }
Exemplo n.º 51
0
 public void CreateWordDictionary(System.IO.FileStream data, System.Xml.Serialization.XmlSerializer serializer)
 {
     wordList = (List <Word>)serializer.Deserialize(data);
 }
Exemplo n.º 52
0
        private void button1_Click(object sender, EventArgs e)
        {
            //    r.dgvr.Columns[0].Name = "№ маршрута";
            //    r.dgvr.Columns[1].Name = "Откуда";
            //    r.dgvr.Columns[2].Name = "Куда";
            //    r.dgvr.Columns[3].Name = "Кол-во проданных билетов";
            //    r.dgvr.Columns[4].Name = "Общая стоимость";
            //    r.dgvr.Columns[5].Name = "Кол-во возврщенных билетов на сумму";
            //    r.dgvr.Columns[6].Name = "На сумму";
            ForReportCashier fr  = new ForReportCashier();
            DateTime         now = DateTime.Now;
            var startDate        = new DateTime(now.Year, now.Month, 1);
            var endDate          = startDate.AddMonths(1).AddDays(-1);

            if ((cbroutsr.Text == "Все"))
            {
                fr.routs = "По маршрутам";
                if (rballc.Checked == true)
                {
                    fr.period = startDate.ToShortDateString() + "-" + endDate.ToShortDateString();
                }
                else
                {
                    fr.period = DateTime.Now.ToShortDateString();
                }
                fr.dateofmaking = DateTime.Now.ToLongDateString();
                for (int i = 0; i < dgvr.Rows.Count - 1; i++)
                {
                    fr.dg.Add(new ForDGVCahier(dgvr[0, i].Value.ToString(), dgvr[1, i].Value + "-" + dgvr[2, i].Value, dgvr[3, i].Value.ToString(), dgvr[5, i].Value.ToString(), (Convert.ToDouble(dgvr[4, i].Value) + Convert.ToDouble(dgvr[6, i].Value)).ToString()));
                }
                System.Xml.Serialization.XmlSerializer writer = new System.Xml.Serialization.XmlSerializer(typeof(ForReportCashier));
                System.IO.StreamWriter file = new System.IO.StreamWriter("2.xml");
                writer.Serialize(file, fr);
                file.Close();
                report r = new report("ReportCashier.frx");
                r.ShowDialog();
            }
            else
            {
                InformationforReport n = new InformationforReport();

                n.rout = tbrc.Text;
                if (rballc.Checked == true)
                {
                    n.fromdate = startDate.ToShortDateString();
                    n.todate   = endDate.ToShortDateString();
                }
                else
                {
                    n.fromdate = DateTime.Now.ToShortDateString();
                    n.todate   = "";
                }
                int q = 0;
                for (int i = 0; i < dgvr.Rows.Count; i++)
                {
                    q += Convert.ToInt32(dgvr[3, i].Value);
                }
                n.quantitysoldticket   = q;
                n.quantityreturnticket = Convert.ToInt32(tbrtcq.Text);
                double qd = 0;
                for (int i = 0; i < dgvr.Rows.Count; i++)
                {
                    qd += Convert.ToDouble(dgvr[4, i].Value);
                }
                n.gain = Math.Round(qd + Convert.ToDouble(tbsum.Text), 2);
                //fm.dgvman.Columns[0].Name = "№ маршрута";
                //fm.dgvman.Columns[1].Name = "Откуда";
                //fm.dgvman.Columns[2].Name = "Куда";
                //fm.dgvman.Columns[3].Name = "Кол-во проданных билетов";
                //fm.dgvman.Columns[4].Name = "Общая стоимость";
                for (int i = 0; i < dgvr.Rows.Count - 1; i++)
                {
                    n.a.Add(new DGVforReport(dgvr[1, i].Value.ToString() + "-" + dgvr[2, i].Value.ToString(), Convert.ToInt32(dgvr[3, i].Value), Convert.ToDouble(dgvr[4, i].Value)));
                }
                System.Xml.Serialization.XmlSerializer writer = new System.Xml.Serialization.XmlSerializer(typeof(InformationforReport));
                System.IO.StreamWriter file = new System.IO.StreamWriter("1.xml");
                writer.Serialize(file, n);
                file.Close();
                report r = new report("ReportSales.frx");
                r.Show();
            }
        }
Exemplo n.º 53
0
        public void Deserialize(string samlResponse)
        {
            ResponseType response = new ResponseType();

            try
            {
                using (TextReader sr = new StringReader(samlResponse))
                {
                    var serializer = new System.Xml.Serialization.XmlSerializer(typeof(ResponseType));
                    response = (ResponseType)serializer.Deserialize(sr);

                    this.Version = response.Version;
                    this.UUID    = response.ID;
                    this.SPUID   = response.InResponseTo;
                    this.Issuer  = response.Issuer.Value;

                    switch (response.Status.StatusCode.Value)
                    {
                    case "urn:oasis:names:tc:SAML:2.0:status:Success":
                        this.RequestStatus = SamlRequestStatus.Success;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:Requester":
                        this.RequestStatus = SamlRequestStatus.RequesterError;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:Responder":
                        this.RequestStatus = SamlRequestStatus.ResponderError;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:VersionMismatch":
                        this.RequestStatus = SamlRequestStatus.VersionMismatchError;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:AuthnFailed":
                        this.RequestStatus = SamlRequestStatus.AuthnFailed;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:InvalidAttrNameOrValue":
                        this.RequestStatus = SamlRequestStatus.InvalidAttrNameOrValue;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:InvalidNameIDPolicy":
                        this.RequestStatus = SamlRequestStatus.InvalidNameIDPolicy;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:NoAuthnContext":
                        this.RequestStatus = SamlRequestStatus.NoAuthnContext;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:NoAvailableIDP":
                        this.RequestStatus = SamlRequestStatus.NoAvailableIDP;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:NoPassive":
                        this.RequestStatus = SamlRequestStatus.NoPassive;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:NoSupportedIDP":
                        this.RequestStatus = SamlRequestStatus.NoSupportedIDP;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:PartialLogout":
                        this.RequestStatus = SamlRequestStatus.PartialLogout;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:ProxyCountExceeded":
                        this.RequestStatus = SamlRequestStatus.ProxyCountExceeded;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:RequestDenied":
                        this.RequestStatus = SamlRequestStatus.RequestDenied;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:RequestUnsupported":
                        this.RequestStatus = SamlRequestStatus.RequestUnsupported;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:RequestVersionDeprecated":
                        this.RequestStatus = SamlRequestStatus.RequestVersionDeprecated;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:RequestVersionTooHigh":
                        this.RequestStatus = SamlRequestStatus.RequestVersionTooHigh;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:RequestVersionTooLow":
                        this.RequestStatus = SamlRequestStatus.RequestVersionTooLow;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:ResourceNotRecognized":
                        this.RequestStatus = SamlRequestStatus.ResourceNotRecognized;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:TooManyResponses":
                        this.RequestStatus = SamlRequestStatus.TooManyResponses;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:UnknownAttrProfile":
                        this.RequestStatus = SamlRequestStatus.UnknownAttrProfile;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:UnknownPrincipal":
                        this.RequestStatus = SamlRequestStatus.UnknownPrincipal;
                        break;

                    case "urn:oasis:names:tc:SAML:2.0:status:UnsupportedBinding":
                        this.RequestStatus = SamlRequestStatus.UnsupportedBinding;
                        break;

                    default:
                        this.RequestStatus = SamlRequestStatus.GenericError;
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 54
0
        public T Read <T>(Stream stream)
        {
            var serializer = new System.Xml.Serialization.XmlSerializer(typeof(T));

            return((T)serializer.Deserialize(stream));
        }
Exemplo n.º 55
0
        public bool Execute()
        {
            //System.Diagnostics.Debugger.Launch();

            Embedded.EnsureAssembliesInitialized();

            AppDomain workerDomain          = null;
            string    serializationAssembly = null;

            try
            {
                workerDomain = AppDomain.CreateDomain("BinarySerialization");

                // http://www.west-wind.com/weblog/posts/2009/Jan/19/Assembly-Loading-across-AppDomains
                AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
                var generator = (CreateBinaryReadersAndWritersTask)workerDomain.CreateInstanceFromAndUnwrap(GetType().Assembly.Location, GetType().FullName);
                AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomain_AssemblyResolve;

                serializationAssembly = generator.Generate(Target, WorkingDirectory, DelaySign, KeyFile, References);
            }
            catch (AggregateException e)
            {
                var serializer = new System.Xml.Serialization.XmlSerializer(typeof(CompilerError));
                foreach (var error in e.InnerExceptions.OfType <InvalidOperationException>().Select(x => FromText(serializer, x.Message)))
                {
                    if (error.IsWarning)
                    {
                        LogWarning(error.ErrorText, error.ErrorNumber, error.FileName, error.Line, error.Column);
                    }
                    else
                    {
                        LogError(error.ErrorText, error.ErrorNumber, error.FileName, error.Line, error.Column);
                    }
                }
                return(false);
            }
            catch (Exception e)
            {
                LogError(e.Message, null, null, 0, 0);
                return(false);
            }
            finally
            {
                if (workerDomain != null)
                {
                    AppDomain.Unload(workerDomain);
                }
            }

            if (serializationAssembly != null)
            {
                LogMessage("Serialization assembly generated", MessageImportance.Normal);

                if (Merge)
                {
                    MergeAssemblies(DelaySign, KeyFile, Target, serializationAssembly);
                    LogMessage("Serialization assemblies merged", MessageImportance.Normal);
                }
            }
            return(true);
        }
Exemplo n.º 56
0
        // Cache configuration file
        private static void CacheConfigurationFile(Tuple <IConfigurationFrame, Action <Exception>, string> args)
        {
            if (args is null)
            {
                return;
            }

            FileStream          configFile         = null;
            IConfigurationFrame configurationFrame = args.Item1;
            Action <Exception>  exceptionHandler   = args.Item2;
            string configurationName          = args.Item3;
            string configurationCacheFileName = GetConfigurationCacheFileName(configurationName);

            try
            {
                // Create multiple backup configurations, if requested
                for (int i = ConfigurationBackups; i > 0; i--)
                {
                    string origConfigFile = $"{configurationCacheFileName}.backup{(i == 1 ? "" : (i - 1).ToString())}";

                    if (File.Exists(origConfigFile))
                    {
                        string nextConfigFile = $"{configurationCacheFileName}.backup{i}";

                        if (File.Exists(nextConfigFile))
                        {
                            File.Delete(nextConfigFile);
                        }

                        File.Move(origConfigFile, nextConfigFile);
                    }
                }
            }
            catch (Exception ex)
            {
                exceptionHandler(new InvalidOperationException($"Failed to create extra backup serialized configuration frames due to exception: {ex.Message}"));
            }

            try
            {
                if (ConfigurationBackups > 0)
                {
                    // Back up current configuration file, if any
                    if (File.Exists(configurationCacheFileName))
                    {
                        string backupConfigFile = $"{configurationCacheFileName}.backup";

                        if (File.Exists(backupConfigFile))
                        {
                            File.Delete(backupConfigFile);
                        }

                        File.Move(configurationCacheFileName, backupConfigFile);
                    }
                }
            }
            catch (Exception ex)
            {
                exceptionHandler(new InvalidOperationException($"Failed to backup last serialized configuration frame due to exception: {ex.Message}"));
            }

            try
            {
                // Serialize configuration frame to a file
                XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(ConfigurationFrame));

                configFile = File.Create(configurationCacheFileName);
                xmlSerializer.Serialize(configFile, configurationFrame);
            }
            catch (Exception ex)
            {
                exceptionHandler(new InvalidOperationException($"Failed to serialize configuration frame: {ex.Message}", ex));
            }
            finally
            {
                configFile?.Close();
            }
        }
Exemplo n.º 57
0
 public static T DeserializeFromXML <T>(Stream xml)
 {
     System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(T));
     return((T)x.Deserialize(xml));
 }
Exemplo n.º 58
0
 public static void Save(TextWriter writer)
 {
     System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(ItemFilterData));
     serializer.Serialize(writer, data);
     writer.Close();
 }
Exemplo n.º 59
0
 public XmlSerializer(Type type)
 {
     _serializer = new System.Xml.Serialization.XmlSerializer(type);
     _namespaces = new XmlSerializerNamespaces();
     _namespaces.Add(string.Empty, string.Empty);
 }
Exemplo n.º 60
0
 private CompilerError FromText(System.Xml.Serialization.XmlSerializer serializer, string text)
 {
     return((CompilerError)serializer.Deserialize(new System.IO.StringReader(text)));
 }