internal static SoftwareModel From(Software software)
 {
     return new SoftwareModel()
     {
         SoftwareId = software.Id,
         Version = software.Version.ToString()
     };
 }
Beispiel #2
0
        public bool CanRegisterSoftware(Software soft)
        {
            if (soft.CapacityConsumption + this.capacityInUse <= this.maxCapacity
                && soft.MemoryConsumption + this.memoryInUse <= this.maxMemory)
            {
                return true;
            }

            return false;
        }
        public IHttpActionResult Post(SoftwareInputModel model)
        {
            var software = new Software(Version.Parse(model.Version), model.Comment);

            SoftwareRepository.Add(software);

            var response = SoftwareModel.From(software);

            return Created(new Uri(Url.Link("GetSoftware", new { softwareId = software.Id })), response);
        }
 public static Common.RSpatialRelation Relation(Software.Triangle a, Plane b)
 {
     var ra = Common.SpatialRelation.Relation(a.A.Position, b);
     var rb = Common.SpatialRelation.Relation(a.B.Position, b);
     var rc = Common.SpatialRelation.Relation(a.C.Position, b);
     if (ra == Common.RSpatialRelation.AInsideB &&
         rb == Common.RSpatialRelation.AInsideB &&
         rc == Common.RSpatialRelation.AInsideB) return Common.RSpatialRelation.AInsideB;
     else if (ra == Common.RSpatialRelation.Outside &&
         rb == Common.RSpatialRelation.Outside &&
         rc == Common.RSpatialRelation.Outside) return Common.RSpatialRelation.Outside;
     else return Common.RSpatialRelation.Intersect;
 }
Beispiel #5
0
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("Testeando insertar productos a la base de datos: ");

                Hardware h1 = new Hardware("Teclado 2.0", 80, 60, 484645);
                Hardware h2 = new Hardware("Pendrive 3.0", 200, 100, 849415);
                Software s1 = new Software("Disney plus", 250, 250, "APOSJPFRPE");
                Software s2 = new Software("Mozilla", 96, 145, "OKDSAOPAKSD");


                Console.WriteLine("Tabla Software actualmente: ");
                Console.WriteLine(Stock.ListarLosProductos(Stock.ListaProductosSoftware));

                Console.WriteLine("Tabla Hardware actualmente: ");
                Console.WriteLine(Stock.ListarLosProductos(Stock.ListaProductosHardware));

                Console.WriteLine("Toque una tecla para continuar");
                Console.WriteLine("----------------------------------------------------------------------------------------------------");
                Console.ReadKey();
                Console.Clear();

                if (Stock.ListaProductosHardware + h1 &&
                    Stock.ListaProductosHardware + h2 &&
                    Stock.ListaProductosSoftware + s1 &&
                    Stock.ListaProductosSoftware + s2)
                {
                    Console.WriteLine("Se insertaron los productos correctamente");
                    Console.WriteLine("Asi estan las tablas ahora: ");

                    Stock.ActualizarListas();

                    Console.WriteLine(" ");
                    Console.WriteLine("Tabla de software:");
                    Console.WriteLine(Stock.ListarLosProductos(Stock.ListaProductosSoftware));

                    Console.WriteLine("Tabla de hardware:");
                    Console.WriteLine(Stock.ListarLosProductos(Stock.ListaProductosHardware));

                    Console.WriteLine("Base de datos actualizada");
                }
                else
                {
                    Console.WriteLine("Alguno de esos prodcutos ya existe en la base de datos");
                }
            }
            catch (DatosErroneosException errorEx)
            {
                Console.WriteLine(errorEx.Message);
            }
            catch (Exception errorGeneral)
            {
                Console.WriteLine(errorGeneral.Message);
            }
            LimpiarPantalla();

            try
            {
                Console.WriteLine("Testeando generar una venta y serializarla");
                Console.WriteLine("");
                Console.WriteLine($"Cantidad de ventas actualmente: {Stock.VentasRealizadas.Count}");
                Console.WriteLine("");

                //Genero numeros random que serviran de indice para elegir un cliente aleatorio y productos aleatorios
                Random random          = new Random();
                int    clienteRandom   = random.Next(0, Stock.Clientes.Count - 1);
                int    productoRandom  = random.Next(0, Stock.ListaProductosSoftware.Count - 1);
                int    producto2Random = random.Next(0, Stock.ListaProductosHardware.Count - 1);

                //Lista que simularia un carrito ya que almacena los prodcutos de la venta
                List <Producto> listaTestVenta = new List <Producto>();

                //Agrego productos random a el carrito
                listaTestVenta.Add(Stock.ListaProductosSoftware[productoRandom]);
                listaTestVenta.Add(Stock.ListaProductosHardware[producto2Random]);

                //Creo una venta
                Venta v1 = new Venta(Stock.GetUltimaIdVentas() + 1,
                                     Stock.Clientes[clienteRandom],
                                     listaTestVenta,
                                     Venta.PrecioFinalCalculado(listaTestVenta));

                //Realiza el descuento a la cantidad del producto elejido
                //Actualiza la base de datos respecto a la cantidad descontada
                //Añade a la lista de ventas dicha venta para luego ser serializada en un archivo xml
                Venta.ConfirmarCompra(v1);

                //Datos de la venta
                Console.WriteLine(v1.ToString());

                //Serializo la lista de ventas
                if (Venta.SerializarVentas())
                {
                    Console.WriteLine("Ventas serializadas en archivo xml");
                }

                Console.WriteLine("Base de datos actualizada");
            }
            catch (DatosErroneosException errorEx)
            {
                Console.WriteLine(errorEx.Message);
            }
            catch (Exception errorGeneral)
            {
                Console.WriteLine(errorGeneral.Message);
            }
            LimpiarPantalla();

            try
            {
                Console.WriteLine("Testendo DatosErroneosException: ");
                Console.WriteLine("");
                Console.WriteLine("Se intentara cargar un numero negativo a el precio");

                Software softTest = new Software("SoftTesting", -10, 10, "FSDFSDFF");
            }
            catch (DatosErroneosException datosErroneos)
            {
                Console.WriteLine(datosErroneos.Message);
            }
            LimpiarPantalla();

            try
            {
                Console.WriteLine("Testendo metodo de extension: ");
                Console.WriteLine("");
                Console.WriteLine("Se intentara ver la cantidad de productos disponibles para vender segun el tipo de producto");

                int stockProductosSoftware = ExtensionList.GetCantidadStockTotal(Stock.ListaProductosSoftware);
                int stockProductosHardware = ExtensionList.GetCantidadStockTotal(Stock.ListaProductosHardware);

                Console.WriteLine("");
                Console.WriteLine($"Stock productos de software: {stockProductosSoftware}");
                Console.WriteLine($"Stock productos de Hardware: {stockProductosHardware}");
            }
            catch (DatosErroneosException datosErroneos)
            {
                Console.WriteLine(datosErroneos.Message);
            }

            LimpiarPantalla();
        }
		public BuildSoftware(string filename)
		{
			filename = Path.GetFileName(filename);

			if (filename.StartsWith(Paths.Prefix, StringComparison.InvariantCultureIgnoreCase))
			{
				filename = filename.Substring(Paths.Prefix.Length);
			}

			if (filename.EndsWith(".tar.gz", StringComparison.InvariantCultureIgnoreCase))
			{
				filename = Str.ReplaceStr(filename, ".tar.gz", "");
			}
			else
			{
				filename = Path.GetFileNameWithoutExtension(filename);
			}
			char[] sps = {'-'};

			string[] tokens = filename.Split(sps, StringSplitOptions.RemoveEmptyEntries);
			if (tokens.Length != 8)
			{
				throw new ApplicationException(filename);
			}

			if (tokens[1].StartsWith("v", StringComparison.InvariantCultureIgnoreCase) == false)
			{
				throw new ApplicationException(filename);
			}

			this.Software = (Software)Enum.Parse(typeof(Software), tokens[0], true);
			this.Version = (int)(double.Parse(tokens[1].Substring(1)) * 100);
			this.BuildNumber = int.Parse(tokens[2]);
			this.BuildName = tokens[3];

			string[] ds = tokens[4].Split('.');
			this.BuildDate = new DateTime(int.Parse(ds[0]), int.Parse(ds[1]), int.Parse(ds[2]));
			this.Os = OSList.FindByName(tokens[5]);
			this.Cpu = CpuList.FindByName(tokens[6]);
		}
Beispiel #7
0
        /// <summary>
        /// Get All Software versions, compatible with a starcounter version or the latest.
        /// If a Suite then the result will contain it's content's versions
        /// </summary>
        /// <param name="software"></param>
        /// <param name="result"></param>
        /// <param name="starcounterVersion"></param>
        private static bool GetSoftwareVersions(Software software, IList<Version> result, string starcounterVersion = null) {

            if (software is App) {

                if (!string.IsNullOrEmpty(starcounterVersion)) {
                    foreach (Version version in software.Versions) {
                        // TODO: Pick the correct version, now we pick the "latest"
                        if (version.IsCompatibleWith(starcounterVersion)) {
                            result.Add(version);
                            return true;
                        }
                    }
                    return false;
                }
                else {
                    foreach (Version version in software.Versions) {
                        result.Add(version);
                    }
                }
                return true;
            }
            else if (software is Suite) {

                QueryResultRows<SuiteSoftware> children = Db.SQL<SuiteSoftware>("SELECT o FROM Warehouse.SuiteSoftware o WHERE o.Suite=?", software);
                foreach (SuiteSoftware child in children) {
                    return GetSoftwareVersions(child.Software, result, starcounterVersion);
                }

            }
            return false;
        }
Beispiel #8
0
 public static BuildSoftware Find(Software soft, OS os, Cpu cpu)
 {
     foreach (BuildSoftware s in List)
     {
         if (s.Software == soft && s.Os == os && s.Cpu == cpu)
         {
             return s;
         }
     }
     return null;
 }
        //================================= read all orders
        public static List <Order> ListOrders()
        {
            List <Order> orders = new List <Order>();

            try
            {
                if (File.Exists(myPath_Order))
                {
                    FileStream   fs          = new FileStream(myPath_Order, FileMode.Open, FileAccess.Read);
                    StreamReader sReader     = new StreamReader(fs);
                    int          recordCount = File.ReadLines(myPath_Order).Count();
                    string       currenRow   = sReader.ReadLine();
                    while (currenRow != null)
                    {
                        string[] currentLineFields = currenRow.Split(',');


                        if (currentLineFields[9] == "software")
                        {
                            Order    o    = new Order();
                            Software soft = new Software();
                            Client   c    = new Client();

                            o.OrderId        = Convert.ToDouble(currentLineFields[0]);
                            soft.ProductID   = currentLineFields[1];
                            soft.ProductName = currentLineFields[2];
                            soft.UnitPrice   = Convert.ToDouble(currentLineFields[4]);

                            c.Name = currentLineFields[3];

                            o.Amount = Convert.ToDouble(currentLineFields[5]);

                            o.RequiredDate = Convert.ToDateTime(currentLineFields[6]);
                            o.ShippingDate = Convert.ToDateTime(currentLineFields[7]);
                            o.Total1       = Convert.ToDouble(currentLineFields[8]);
                            o.TitleOrder   = currentLineFields[9];
                            o.Status       = currentLineFields[10];

                            o.Software = soft;
                            o.Client   = c;
                            orders.Add(o);
                        }
                        else if (currentLineFields[9] == "book")
                        {
                            Order  o    = new Order();
                            Book   book = new Book();
                            Client c    = new Client();

                            o.OrderId        = Convert.ToDouble(currentLineFields[0]);
                            book.ProductID   = currentLineFields[1];
                            book.ProductName = currentLineFields[2];
                            book.UnitPrice   = Convert.ToDouble(currentLineFields[4]);

                            c.Name = currentLineFields[3];

                            o.Amount = Convert.ToDouble(currentLineFields[5]);

                            o.RequiredDate = Convert.ToDateTime(currentLineFields[6]);
                            o.ShippingDate = Convert.ToDateTime(currentLineFields[7]);
                            o.Total1       = Convert.ToDouble(currentLineFields[8]);
                            o.TitleOrder   = currentLineFields[9];

                            o.Status = currentLineFields[10];
                            o.Book   = book;
                            o.Client = c;
                            orders.Add(o);
                        }
                        currenRow = sReader.ReadLine();
                    }
                    sReader.Close();
                    fs.Close();
                }

                return(orders);
            }
            catch
            {
                return(null);
            }
        }
 public EditSoftwareWindow(Software obj, int i)
 {
     this.s = obj;
     index  = i;
     InitializeComponent();
 }
        public IHttpActionResult PutSoftware(int id, Software software)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != software.SoftwareId)
            {
                return BadRequest();
            }

            if (!ManufacturerExists(software.ManufacturerId))
            {
                return BadRequest("Manufacturer not exists");
            }

            _db.MarkAsModified(software);

            try
            {
                _db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                Logger.Error(ex);
                //TODO check if software exits
                return NotFound();
            }

            return StatusCode(HttpStatusCode.NoContent);
        }
 private void btnEditSoftw_Click(object sender, EventArgs e)
 {
     Software aSoftware = new Software();
     Form aNewSoftware = new SoftwareForm(aSoftware, 2);
     aNewSoftware.Show();
 }
Beispiel #13
0
        /// <summary>
        /// Create a new mapper based on the XML file type and version.
        /// </summary>
        public static Mapper Create( string xml, Software sw )
        {
            const int size = 2000;
            char[] buffer = new char[size];
            TextReader tr = new StreamReader( xml );
            tr.ReadBlock( buffer, 0, size );
            tr.Close();

            // PLGS
            string str = new string(buffer);
            if( str.Contains("GeneratedBy") )
            return new Plgs(sw);

            // mzIdentML 1.1 and 1.2
            int i = str.IndexOf( "MzIdentML" );
            string version;
            if( i != -1 ) {
            str = str.Remove(0,i);
            i = str.IndexOf( "version" );
            if( i == -1 )
                throw new ApplicationException( "mzIdentML version not provided" );
            str = str.Remove(0,i);
            version = str.Split(new char[]{'"'})[1];
            switch( version ) {
                case "1.1.0":
                    return new mzId1_1(sw);
                case "1.2.0":
                    return new mzId1_2(sw);
            }
            throw new ApplicationException( "mzIdentML version '" + version + "' not supported" );
            }

            // mzIdentML 1.0
            str = new string(buffer);
            i = str.IndexOf( "mzIdentML" );
            if( i == -1 )
            throw new ApplicationException( "Identification file format not supported" );
            str = str.Remove(0,i);
            i = str.IndexOf( "version" );
            if( i == -1 )
            throw new ApplicationException( "mzIdentML version not provided" );
            str = str.Remove(0,i);
            version = str.Split(new char[]{'"'})[1];
            switch( version ) {
            case "1.0.0":
                return new mzId1_0(sw);
            }
            throw new ApplicationException( "mzIdentML version '" + version + "' not supported" );
        }
Beispiel #14
0
 /// <summary>
 /// Default constructor
 /// </summary>
 public Mapper( Software sw )
 {
     m_Software = sw;
     Proteins = new List<Protein>();
     Peptides = new List<Peptide>();
     Spectra = new List<Spectrum>();
     m_Stats = new StatsStruct();
     m_Format = new System.Globalization.NumberFormatInfo();
     m_Format.NumberDecimalSeparator = ".";
     m_Run = 0;
     m_Type = SourceType.Unknown;
     LengthThreshold = 0;
     PlgsThreshold = Peptide.ConfidenceType.NoThreshold;
     SeqThreshold = Peptide.ConfidenceType.NoThreshold;
     XTandemThreshold = 0.05;
     XTandemAvailable = false;
     MascotThreshold = 0.05;
     MascotAvailable = false;
     RequirePassTh = true;
     RankThreshold = 0;
     FilterDecoys = true;
     RunsThreshold = 1;
     m_InputFiles = new List<string>();
 }
Beispiel #15
0
        /// <summary>
        /// unpack image from package
        /// TODO: Assure random filename is unique
        /// </summary>
        /// <param name="packageZip"></param>
        /// <param name="config"></param>
        /// <param name="destination"></param>
        /// <param name="url"></param>
        private static void UnpackAppStoreMetadata(Software software, string packageZip, PackageConfigFile config, string destination) {

            string fileName = Path.GetRandomFileName();
            if (!Directory.Exists(destination)) {
                Directory.CreateDirectory(destination);
            }
            //string destinationFileName = Path.Combine(destination, fileName);
            //destinationFileName = Path.ChangeExtension(destinationFileName, Path.GetExtension(config.ImageUri));

            Dictionary<string, string> icons = new Dictionary<string, string>();
            Dictionary<string, string> banners = new Dictionary<string, string>();
            Dictionary<string, string> screenshots = new Dictionary<string, string>();
            Dictionary<string, string> appstoreicons = new Dictionary<string, string>();


            string metadataFolder = "metadata/";
            string bannerMap = "banner";
            string screenshotMap = "screenshot";
            string appiconMap = "appicon";

            using (ZipArchive archive = ZipFile.OpenRead(packageZip)) {

                #region Find Media
                foreach (ZipArchiveEntry entry in archive.Entries) {

                    if (entry.FullName.Equals(config.ImageUri, StringComparison.InvariantCultureIgnoreCase)) {
                        // Icon
                        string uniqueFileName;
                        string extention = Path.GetExtension(entry.FullName);
                        Utils.GetUniqueFilename(destination, extention, out uniqueFileName);
                        icons.Add(entry.FullName, uniqueFileName);
                    }

                    if (entry.FullName.StartsWith(metadataFolder + bannerMap, StringComparison.InvariantCultureIgnoreCase)) {
                        // Banner
                        string uniqueFileName;
                        string extention = Path.GetExtension(entry.FullName);
                        Utils.GetUniqueFilename(destination, extention, out uniqueFileName);
                        banners.Add(entry.FullName, uniqueFileName);
                    }

                    if (entry.FullName.StartsWith(metadataFolder + screenshotMap, StringComparison.InvariantCultureIgnoreCase)) {
                        // Screenshot
                        string uniqueFileName;
                        string extention = Path.GetExtension(entry.FullName);
                        Utils.GetUniqueFilename(destination, extention, out uniqueFileName);
                        screenshots.Add(entry.FullName, uniqueFileName);
                    }

                    if (entry.FullName.StartsWith(metadataFolder + appiconMap, StringComparison.InvariantCultureIgnoreCase)) {

                        // Appstoreicon
                        string uniqueFileName;
                        string extention = Path.GetExtension(entry.FullName);
                        Utils.GetUniqueFilename(destination, extention, out uniqueFileName);
                        appstoreicons.Add(entry.FullName, uniqueFileName);
                    }

                }
                #endregion

                #region Unpack
                foreach (var item in icons) {

                    PackageManager.UnpackFile(archive, item.Key, item.Value);

                    string hash = Utils.CalculateHash(item.Value);

                    // Dup check
                    SoftwareIcon softwareIcon = Db.SQL<SoftwareIcon>("SELECT o FROM Warehouse.SoftwareIcon o WHERE o.Software=? AND o.Hash=?", software, hash).First;
                    if (softwareIcon != null) {
                        // Delete new file
                        File.Delete(item.Value);
                    }
                    else {
                        SoftwareIcon img = new SoftwareIcon();
                        img.Software = software;
                        img.File = item.Value;
                        img.Position = 0;
                        img.Hash = hash;
                    }
                }

                foreach (var item in banners) {

                    PackageManager.UnpackFile(archive, item.Key, item.Value);

                    string hash = Utils.CalculateHash(item.Value);
                    SoftwareBanner img = Db.SQL<SoftwareBanner>("SELECT o FROM Warehouse.SoftwareBanner o WHERE o.Software=? AND o.Hash=?", software, hash).First;
                    if (img != null) {
                        // Delete new file
                        File.Delete(item.Value);
                    }
                    else {
                        img = new SoftwareBanner();
                        img.Software = software;
                        img.File = item.Value;
                        img.Hash = hash;
                    }

                    try {
                        string fName = Path.GetFileNameWithoutExtension(item.Key).Substring(bannerMap.Length);
                        fName = fName.Trim(new Char[] { ' ', '-', '_' });
                        img.Position = int.Parse(fName);
                    }
                    catch (Exception) { }
                }

                foreach (var item in screenshots) {

                    PackageManager.UnpackFile(archive, item.Key, item.Value);
                    string hash = Utils.CalculateHash(item.Value);
                    SoftwareScreenshot img = Db.SQL<SoftwareScreenshot>("SELECT o FROM Warehouse.SoftwareScreenshot o WHERE o.Software=? AND o.Hash=?", software, hash).First;
                    if (img != null) {
                        // Delete new file
                        File.Delete(item.Value);
                    }
                    else {
                        img = new SoftwareScreenshot();
                        img.Software = software;
                        img.File = item.Value;
                        img.Hash = hash;
                    }

                    try {
                        string fName = Path.GetFileNameWithoutExtension(item.Key).Substring(screenshotMap.Length);
                        fName = fName.Trim(new Char[] { ' ', '-', '_' });
                        img.Position = int.Parse(fName);
                    }
                    catch (Exception) { }
                }

                foreach (var item in appstoreicons) {

                    PackageManager.UnpackFile(archive, item.Key, item.Value);
                    string hash = Utils.CalculateHash(item.Value);

                    SoftwareIcon img = Db.SQL<SoftwareIcon>("SELECT o FROM Warehouse.SoftwareIcon o WHERE o.Software=? AND o.Hash=?", software, hash).First;
                    if (img != null) {
                        // Delete new file
                        File.Delete(item.Value);
                    }
                    else {
                        img = new SoftwareIcon();
                        img.Software = software;
                        img.File = item.Value;
                        img.Hash = hash;
                    }

                    try {
                        string fName = Path.GetFileNameWithoutExtension(item.Key).Substring(appiconMap.Length);
                        fName = fName.Trim(new Char[] { ' ', '-', '_' });
                        img.Position = int.Parse(fName);
                    }
                    catch (Exception) { }
                }
                #endregion
            }
        }
 public void DrawLines(Software.Vertex.Position3[] lines, Color color)
 {
     Software.Mesh mesh = new Graphics.Software.Mesh
     {
         MeshType = Graphics.MeshType.LineStrip,
         NVertices = lines.Length,
         NFaces = lines.Length - 1,
         VertexStreamLayout = Software.Vertex.Position3.Instance,
         VertexBuffer = new Software.VertexBuffer<Software.Vertex.Position3>(lines)
     };
     var m = Content.MeshConcretize.Concretize10(view.Content, mesh, mesh.VertexStreamLayout);
     DrawLines(m, color);
     m.Dispose();
 }
 public AuditTrailEntryBuilder WihtSoftware(Software software)
 {
     this.auditTrailEntry.Software = software;
     return(this);
 }
        public IHttpActionResult PostSoftware(Software software)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (!ManufacturerExists(software.ManufacturerId))
            {
                return BadRequest("Manufacturer not exists");
            }

            _db.Softwares.Add(software);
            _db.SaveChanges();

            //TODO checked created at route
            //return CreatedAtRoute("DefaultApi", new {id = software.SoftwareId}, software);
            return Created("api/softwares/" + new { id = software.SoftwareId }, software);
        }
Beispiel #19
0
        // Get a product list that is included in the software
        public static string GetSoftwareProductList(Software soft)
        {
            string ret = "";

            switch (soft)
            {
                case Software.vpnbridge:
                    ret = "PacketiX VPN Bridge";
                    break;

                case Software.vpnclient:
                    ret = "PacketiX VPN Client, PacketiX VPN Command-Line Admin Utility (vpncmd)";
                    break;

                case Software.vpnserver:
                    ret = "PacketiX VPN Server, PacketiX VPN Command-Line Admin Utility (vpncmd)";
                    break;

                case Software.vpnserver_vpnbridge:
                    ret = "PacketiX VPN Server, PacketiX VPN Bridge, PacketiX VPN Server Manager for Windows, PacketiX VPN Command-Line Admin Utility (vpncmd)";
                    break;

                default:
                    throw new ApplicationException("invalid soft.");
            }

            #if BU_SOFTETHER
            ret = Str.ReplaceStr(ret, "PacketiX", "SoftEther", false);
            #endif

            return ret;
        }
 public void AddSoftware(Software software)
 {
     _db.Softwares.Add(software);
     _db.SaveChanges();
 }
Beispiel #21
0
        static void Main()
        {
            var software = new Software();

            software.Start();
        }
 public void DeleteSoftware(Software software)
 {
     _db.Softwares.Remove(software);
     _db.SaveChanges();
 }
 public static bool Intersect(Ray a, Software.Mesh b, out object intersection)
 {
     var r = new Common.RayIntersection();
     intersection = r;
     Software.Triangle t;
     Vector2 uv;
     bool hit = b.Intersect(a, false, out t, out r.Distance, out uv);
     r.Userdata = uv;
     return hit;
 }
 public void UpdateSoftware(Software software)
 {
     _db.Entry(software).State = EntityState.Modified;
     _db.SaveChanges();
 }
Beispiel #25
0
        private void gridView_ShowCellToolTip(DataGridViewCell cell)
        {
            MassSpectrum spectrum = cell.OwningRow.Tag as MassSpectrum;
            Spectrum     s        = spectrum.Element;

            TreeViewForm treeViewForm = new TreeViewForm(spectrum);
            TreeView     tv           = treeViewForm.TreeView;

            if (gridView.Columns[cell.ColumnIndex].Name == "PrecursorInfo")
            {
                treeViewForm.Text = "Precursor Details";
                if (s.precursors.Count == 0)
                {
                    tv.Nodes.Add("No precursor information available.");
                }
                else
                {
                    foreach (Precursor p in s.precursors)
                    {
                        string pNodeText = "Precursor scan";
                        if (p.sourceFile != null && p.externalSpectrumID.Length > 0)
                        {
                            pNodeText += String.Format(": {0}:{1}", p.sourceFile.name, p.externalSpectrumID);
                        }
                        else if (p.spectrumID.Length > 0)
                        {
                            pNodeText += String.Format(": {0}", p.spectrumID);
                        }

                        TreeNode pNode = tv.Nodes.Add(pNodeText);
                        addParamsToTreeNode(p as ParamContainer, pNode);

                        if (p.selectedIons.Count == 0)
                        {
                            pNode.Nodes.Add("No selected ion list available.");
                        }
                        else
                        {
                            foreach (SelectedIon si in p.selectedIons)
                            {
                                TreeNode siNode = pNode.Nodes.Add("Selected ion");
                                //siNode.ToolTipText = new CVTermInfo(CVID.MS_selected_ion); // not yet in CV
                                addParamsToTreeNode(si as ParamContainer, siNode);
                            }
                        }

                        if (p.activation.empty())
                        {
                            pNode.Nodes.Add("No activation details available.");
                        }
                        else
                        {
                            TreeNode actNode = pNode.Nodes.Add("Activation");
                            addParamsToTreeNode(p.activation as ParamContainer, actNode);
                        }

                        if (p.isolationWindow.empty())
                        {
                            pNode.Nodes.Add("No isolation window details available.");
                        }
                        else
                        {
                            TreeNode iwNode = pNode.Nodes.Add("Isolation Window");
                            addParamsToTreeNode(p.isolationWindow as ParamContainer, iwNode);
                        }
                    }
                }
            }
            else if (gridView.Columns[cell.ColumnIndex].Name == "ScanInfo")
            {
                treeViewForm.Text = "Scan Configuration Details";
                if (s.scanList.empty())
                {
                    tv.Nodes.Add("No scan details available.");
                }
                else
                {
                    TreeNode slNode = tv.Nodes.Add("Scan List");
                    addParamsToTreeNode(s.scanList as ParamContainer, slNode);

                    foreach (Scan scan in s.scanList.scans)
                    {
                        TreeNode scanNode = slNode.Nodes.Add("Acquisition");
                        addParamsToTreeNode(scan as ParamContainer, scanNode);

                        foreach (ScanWindow sw in scan.scanWindows)
                        {
                            TreeNode swNode = scanNode.Nodes.Add("Scan Window");
                            addParamsToTreeNode(sw as ParamContainer, swNode);
                        }
                    }
                }
            }
            else if (gridView.Columns[cell.ColumnIndex].Name == "InstrumentConfigurationID")
            {
                treeViewForm.Text = "Instrument Configuration Details";
                InstrumentConfiguration ic = s.scanList.scans[0].instrumentConfiguration;
                if (ic == null || ic.empty())
                {
                    tv.Nodes.Add("No instrument configuration details available.");
                }
                else
                {
                    TreeNode icNode = tv.Nodes.Add(String.Format("Instrument Configuration ({0})", ic.id));
                    addParamsToTreeNode(ic as ParamContainer, icNode);

                    if (ic.componentList.Count == 0)
                    {
                        icNode.Nodes.Add("No component list available.");
                    }
                    else
                    {
                        TreeNode clNode = icNode.Nodes.Add("Component List");
                        foreach (pwiz.CLI.msdata.Component c in ic.componentList)
                        {
                            string cNodeText;
                            switch (c.type)
                            {
                            case ComponentType.ComponentType_Source:
                                cNodeText = "Source";
                                break;

                            case ComponentType.ComponentType_Analyzer:
                                cNodeText = "Analyzer";
                                break;

                            default:
                            case ComponentType.ComponentType_Detector:
                                cNodeText = "Detector";
                                break;
                            }
                            TreeNode cNode = clNode.Nodes.Add(cNodeText);
                            addParamsToTreeNode(c as ParamContainer, cNode);
                        }
                    }

                    Software sw = ic.software;
                    if (sw == null || sw.empty())
                    {
                        icNode.Nodes.Add("No software details available.");
                    }
                    else
                    {
                        TreeNode swNode        = icNode.Nodes.Add(String.Format("Software ({0})", sw.id));
                        CVParam  softwareParam = sw.cvParamChild(CVID.MS_software);
                        TreeNode swNameNode    = swNode.Nodes.Add("Name: " + softwareParam.name);
                        swNameNode.ToolTipText = new CVTermInfo(softwareParam.cvid).def;
                        swNode.Nodes.Add("Version: " + sw.version);
                    }
                }
            }
            else if (gridView.Columns[cell.ColumnIndex].Name == "DataProcessing")
            {
                treeViewForm.Text = "Data Processing Details";
                DataProcessing dp = s.dataProcessing;
                if (dp == null || dp.empty())
                {
                    tv.Nodes.Add("No data processing details available.");
                }
                else
                {
                    TreeNode dpNode = tv.Nodes.Add(String.Format("Data Processing ({0})", dp.id));

                    if (dp.processingMethods.Count == 0)
                    {
                        dpNode.Nodes.Add("No component list available.");
                    }
                    else
                    {
                        TreeNode pmNode = dpNode.Nodes.Add("Processing Methods");
                        foreach (ProcessingMethod pm in dp.processingMethods)
                        {
                            addParamsToTreeNode(pm as ParamContainer, pmNode);
                        }
                    }
                }
            }
            else
            {
                return;
            }

            tv.ExpandAll();
            treeViewForm.StartPosition = FormStartPosition.CenterParent;
            treeViewForm.AutoSize      = true;
            //treeViewForm.DoAutoSize();
            treeViewForm.Show(this.DockPanel);
            //leaveTimer.Start();
            this.Focus();
        }
Beispiel #26
0
 public AddIn(Software software, BlockingCollection <WorkItem> workQueue)
 {
     _software       = software;
     _workQueue      = workQueue;
     _software.Idle += OnSoftwareIdle;
 }
		public DateTime BuildDate;				// Build date

		public BuildSoftware(Software software, int buildNumber, int version, string buildName, Cpu cpu, OS os)
		{
			this.Software = software;
			this.BuildNumber = buildNumber;
			this.Version = version;
			this.BuildName = buildName;
			this.Cpu = cpu;
			this.Os = os;
		}
Beispiel #28
0
 public ApiController(Software software, BlockingCollection <WorkItem> workQueue)
 {
     _software  = software;
     _workQueue = workQueue;
 }
Beispiel #29
0
        public static void Main(string[] args)
        {
            PersonalComputer myPc = new PersonalComputer();

            myPc.Guarantee  = 2;
            myPc.Price      = 1000;
            myPc.Provider   = "World PC";
            myPc.HardwarePc = new List <Hardware>();

            // setting screen
            Screen myScreen = new Screen();

            myScreen.Brand = "Samsung";
            myPc.HardwarePc.Add(myScreen);

            // setting keyboard
            Keyboard myKeyboard = new Keyboard();

            myKeyboard.Brand = "Genius";
            myPc.HardwarePc.Add(myKeyboard);

            // setting mouse
            Mouse myMouse = new Mouse();

            myMouse.Brand = "Genius";
            myPc.HardwarePc.Add(myMouse);

            // setting case
            Case myCase = new Case();

            myCase.Brand = "Ducky";
            myPc.HardwarePc.Add(myCase);

            // setting camera
            Camera myCamera = new Camera();

            myCamera.Color = "Silver";
            myPc.HardwarePc.Add(myCamera);

            // setting speaker
            Speaker mySpeaker = new Speaker();

            mySpeaker.Frequency = 100;
            myPc.HardwarePc.Add(mySpeaker);
            myPc.SoftwarePc = new List <Software>();

            // setting softwareOS
            Software mySoftwareOS = new Software();

            mySoftwareOS.Version    = 2;
            mySoftwareOS.LastUpdate = DateTime.Now.AddYears(-10);
            mySoftwareOS.Name       = "Windows XP";
            myPc.SoftwarePc.Add(mySoftwareOS);
            Software mySoftwareApp = new Software();

            mySoftwareApp.Version    = 5;
            mySoftwareApp.LastUpdate = DateTime.Now.AddYears(-2);
            mySoftwareApp.Name       = "League of Legends";
            mySoftwareApp.Release    = DateTime.Now.AddYears(-8);
            myPc.SoftwarePc.Add(mySoftwareApp);
            User myUser = new User();

            myUser.FirstName   = "Bill";
            myUser.LastName    = "Gates";
            myUser.UserName    = "******";
            mySoftwareOS.Users = new List <User>();
            mySoftwareOS.Users.Add(myUser);
            myScreen.Brand = "Samsung";
            myPc.HardwarePc.Add(myScreen);
        }
Beispiel #30
0
 public void Adiciona(Software software)
 {
     contexto.Softwares.Add(software);
     contexto.SaveChanges();
 }
Beispiel #31
0
        public ActionResult New(string typeId)
        {
            if (typeId == "Default")
            {
                return(View("ItemForm"));
            }

            if (typeId == "Desktop")
            {
                Desktop desktop = new Desktop();
                return(View("DesktopForm", desktop));
            }

            if (typeId == "Camera")
            {
                Camera camera = new Camera();
                return(View("CameraForm", camera));
            }

            if (typeId == "CarryingBag")
            {
                CarryingBag carryingBag = new CarryingBag();
                return(View("CarryingBagForm", carryingBag));
            }

            if (typeId == "GameConsole")
            {
                GameConsole gameConsole = new GameConsole();
                return(View("GameConsoleForm", gameConsole));
            }

            if (typeId == "Laptop")
            {
                Laptop laptop = new Laptop();
                return(View("LaptopForm", laptop));
            }

            if (typeId == "MajorAppliance")
            {
                MajorAppliance majorAppliance = new MajorAppliance();
                return(View("MajorApplianceForm", majorAppliance));
            }

            if (typeId == "MouseAndKeyBoard")
            {
                MouseAndKeyBoard mouseAndKeyBoard = new MouseAndKeyBoard();
                return(View("MouseAndKeyBoardForm", mouseAndKeyBoard));
            }

            if (typeId == "Movie")
            {
                Movie movie = new Movie();
                return(View("MovieForm", movie));
            }

            if (typeId == "Software")
            {
                Software software = new Software();
                return(View("SoftwareForm", software));
            }

            if (typeId == "VideoGame")
            {
                VideoGame videoGame = new VideoGame();
                return(View("VideoGameForm", videoGame));
            }


            return(View("ItemForm"));
        }
Beispiel #32
0
 public void Remover(Software software)
 {
     contexto.Softwares.Remove(software);
     contexto.SaveChanges();
 }
Beispiel #33
0
 public BuildSoftwareWin32(Software software, int buildNumber, int version, string buildName, Cpu cpu, OS os)
     : base(software, buildNumber, version, buildName, cpu, os)
 {
 }
Beispiel #34
0
 public void Atualiza(Software Softwares)
 {
     contexto.Entry(Softwares).State = EntityState.Modified;
     contexto.Softwares.Update(Softwares);
     contexto.SaveChanges();
 }
        public IActionResult Create(SoftwareViewModel model)
        {
            if (model.SoftwareCPURequirements == null)
            {
                model.SoftwareCPURequirements = new List <SoftwareCPURequirement>();
            }
            if (model.SoftwareVideoCardRequirements == null)
            {
                model.SoftwareVideoCardRequirements = new List <SoftwareVideoCardRequirement>();
            }
            if (model.MinimiumRequiredRAM > model.RecommendedRequiredRAM)
            {
                ModelState.AddModelError("MinimiumRequiredRAM", "Мінімальні вимоги не можуть бути кращими за рекомендовані");
            }
            var newMinCpus = model.SoftwareCPURequirements.Where(m => m.RequirementTypeId == 1).Select(m => _cpuService.GetCPU(m.CPUId));
            var newReqCpus = model.SoftwareCPURequirements.Where(m => m.RequirementTypeId == 2).Select(m => _cpuService.GetCPU(m.CPUId));
            var newMinVC   = model.SoftwareVideoCardRequirements.Where(m => m.RequirementTypeId == 1).Select(m => _videoCardService.GetVideoCard(m.VideoCardId));
            var newReqVC   = model.SoftwareVideoCardRequirements.Where(m => m.RequirementTypeId == 2).Select(m => _videoCardService.GetVideoCard(m.VideoCardId));

            if (newMinCpus.Any(m => newReqCpus.Any(z => m.Frequency > z.Frequency || m.ThreadsNumber > z.ThreadsNumber || m.CoresNumber > z.CoresNumber)))
            {
                ModelState.AddModelError("SoftwareCPURequirements", "Мінімальні вимоги не можуть бути кращими за рекомендовані");
            }
            if (newMinVC.Any(m => newReqVC.Any(z => m.Frequency > z.Frequency || m.MemoryFrequency > z.MemoryFrequency || m.MemorySize > z.MemorySize)))
            {
                ModelState.AddModelError("SoftwareVideoCardRequirements", "Мінімальні вимоги не можуть бути кращими за рекомендовані");
            }
            if (ModelState.IsValid)
            {
                var helper      = new ImageHelper(_webHostEnvironment);
                var image       = helper.GetUploadedFile(model.Image, "Software");
                var powerSupply = new Software()
                {
                    Name                   = model.Name,
                    Description            = model.Description,
                    DiscVolume             = model.DiscVolume,
                    MinimiumRequiredRAM    = model.MinimiumRequiredRAM,
                    RecommendedRequiredRAM = model.RecommendedRequiredRAM,
                    PublisherId            = model.PublisherId,
                    DeveloperId            = model.DeveloperId,
                    Image                  = image,
                    Price                  = model.Price
                };

                powerSupply.SoftwareCPURequirements = model.SoftwareCPURequirements.Select(m => new SoftwareCPURequirement()
                {
                    CPUId = m.CPUId, RequirementTypeId = m.RequirementTypeId
                }).ToList();
                powerSupply.SoftwareVideoCardRequirements = model.SoftwareVideoCardRequirements.Select(m => new SoftwareVideoCardRequirement()
                {
                    VideoCardId = m.VideoCardId, RequirementTypeId = m.RequirementTypeId
                }).ToList();

                var result = _softwareService.CreateSoftware(powerSupply);

                if (result.Succedeed)
                {
                    return(View("../Catalog/Index", new { startView = "Software" }));
                }

                return(NotFound(result));
            }
            var cpus = _cpuService.GetCPUs();

            ViewBag.CPUs = new SelectList(cpus, "Id", "Name");
            var videoCards = _videoCardService.GetVideoCards();

            ViewBag.VideoCards = new SelectList(videoCards, "Id", "Name");
            var publishers = _publisherService.GetPublishers();

            ViewBag.Publishers = new SelectList(publishers, "Id", "Name");
            var developers = _developerService.GetDevelopers();

            ViewBag.Developers = new SelectList(developers, "Id", "Name");
            return(View(model));
        }
Beispiel #36
0
        public async Task Can_Add_Subscription_Thought_UnitOfWork()
        {
            //Arrange
            var customer = new Customer()
            {
                CustomerEMail = "*****@*****.**", CustomerIsActive = true, CustomerName = "Adý soyadý", CustomerPhone = "123123"
            };
            var customerResult = await _customerManager.SaveCustomer(customer);

            Assert.True(customerResult.Status);

            var software = new Software()
            {
                SoftwareLastVersion = "v123", SoftwareName = "twitter", SoftwareIsActive = true,
            };
            var softwareResult = await _softwareManager.SaveSoftware(software);

            Assert.True(softwareResult.Status);

            var subscription = new Subscription()
            {
                CustomerId = customer.CustomerId, SoftwareId = software.SoftwareId, SubscriptionId = 0, SubScriptionEndDate = DateTime.Now.AddDays(2), SubScriptionLicenceCount = 2, SubScriptionStartDate = DateTime.Now,
            };
            var subscriptionResult = await _subscriptionManager.SaveSubscription(subscription);

            Assert.True(subscriptionResult.Status);

            var customerComputerInfo = new CustomerComputerInfo()
            {
                SubscriptionId                        = subscription.SubscriptionId,
                CustomerComputerInfoId                = 0,
                CustomerComputerInfoHddSerialCode     = "hddcode1234",
                CustomerComputerInfoMacSerialCode     = "maccode1234",
                CustomerComputerInfoProcessSerialCode = "processserialcode1234",
            };

            //Action
            var result = await _customerComputerInfoManager.SaveCustomerComputerInfo(customerComputerInfo);

            //Asserts
            if (result.Status == false)
            {
                _outputHelper.WriteLine(result.Message);
            }

            Assert.True(result.Status);
            Assert.True(customerComputerInfo.CustomerComputerInfoId > 0);

            await Can_Delete_Exists_CustomerComputerInfo_Thought_UnitOfWork(customerComputerInfo.CustomerComputerInfoId);

            var customerDeleteResult = await _customerManager.DeleteCustomerByCustomerId(customer.CustomerId);

            Assert.True(customerDeleteResult.Status);

            var subscriptionDeleteResult = await _subscriptionManager.DeleteSubscriptionBySubscriptionId(subscription.SubscriptionId);

            Assert.True(subscriptionDeleteResult.Status);

            var softwareDeleteResult = await _softwareManager.DeleteSoftwareBySoftwareId(software.SoftwareId);

            Assert.True(softwareDeleteResult.Status);
        }
        protected override void Seed(MainBCUnitOfWork unitOfWork)
        {
            /*
             * Countries agg
             */

            var spainCountry = new Country("Spain", "es-ES");

            spainCountry.ChangeCurrentIdentity(new Guid("32BB805F-40A4-4C37-AA96-B7945C8C385C"));

            var usaCountry = new Country("EEUU", "en-US");

            usaCountry.ChangeCurrentIdentity(new Guid("C3C82D06-6A07-41FB-B7EA-903EC456BFC5"));

            unitOfWork.Countries.Add(spainCountry);
            unitOfWork.Countries.Add(usaCountry);

            /*
             * Customers agg
             */

            var customerJhon = CustomerFactory.CreateCustomer("Jhon", "Jhon", "+34617", "company", spainCountry, new Address("Madrid", "280181", "Paseo de La finca", ""));

            customerJhon.ChangeCurrentIdentity(new Guid("43A38AC8-EAA9-4DF0-981F-2685882C7C45"));


            var customerMay = CustomerFactory.CreateCustomer("May", "Garcia", "+34617", "company", usaCountry, new Address("Seatle", "3332", "Alaskan Way", ""));

            customerMay.ChangeCurrentIdentity(new Guid("0CD6618A-9C8E-4D79-9C6B-4AA69CF18AE6"));


            unitOfWork.Customers.Add(customerJhon);
            unitOfWork.Customers.Add(customerMay);


            /*
             * Product agg
             */
            var book = new Book("The book title", "Any book description", "Krassis Press", "ABC");

            book.ChangeUnitPrice(40M);
            book.IncrementStock(2);

            book.ChangeCurrentIdentity(new Guid("44668EBF-7B54-4431-8D61-C1298DB50857"));

            var software = new Software("the new SO", "the software description", "XXXX0000--111");

            software.ChangeUnitPrice(100M);
            software.IncrementStock(3);
            software.ChangeCurrentIdentity(new Guid("D7E5C537-6A0C-4E19-B41E-3653F4998085"));

            unitOfWork.Products.Add(book);
            unitOfWork.Products.Add(software);

            /*
             * Orders agg
             */

            var orderA = OrderFactory.CreateOrder(customerJhon, "shipping name", "shipping city", "shipping address", "shipping zip code");

            orderA.ChangeCurrentIdentity(new Guid("3135513C-63FD-43E6-9697-6C6E5D8CE55B"));
            orderA.OrderDate = DateTime.Now;

            orderA.AddNewOrderLine(book.Id, 1, 40, 0);

            var orderB = OrderFactory.CreateOrder(customerMay, "shipping name", "shipping city", "shipping address", "shipping zip code");

            orderB.GenerateNewIdentity();
            orderB.OrderDate = DateTime.Now;

            orderB.AddNewOrderLine(software.Id, 3, 12, 0);

            unitOfWork.Orders.Add(orderA);
            unitOfWork.Orders.Add(orderB);

            /*
             * Bank Account agg
             */

            var         bankAccountNumberJhon = new BankAccountNumber("1111", "2222", "3333333333", "01");
            BankAccount bankAccountJhon       = BankAccountFactory.CreateBankAccount(customerJhon, bankAccountNumberJhon);

            bankAccountJhon.ChangeCurrentIdentity(new Guid("0343C0B0-7C40-444A-B044-B463F36A1A1F"));
            bankAccountJhon.DepositMoney(1000, "Open BankAccount");

            var         bankAccountNumberMay = new BankAccountNumber("4444", "5555", "3333333333", "02");
            BankAccount bankAccountMay       = BankAccountFactory.CreateBankAccount(customerMay, bankAccountNumberMay);

            bankAccountMay.GenerateNewIdentity();
            bankAccountJhon.DepositMoney(2000, "Open BankAccount");

            unitOfWork.BankAccounts.Add(bankAccountJhon);
            unitOfWork.BankAccounts.Add(bankAccountMay);
        }
        public override void Activation()
        {
            base.Activation();

            // Service
            {
                ServiceController service = null;
                try
                {
                    service         = new ServiceController("MpsSvc");
                    m_serviceStatus = (service.Status == ServiceControllerStatus.Running);
                    if (m_serviceStatus == false)
                    {
                        TimeSpan timeout = TimeSpan.FromMilliseconds(10000);
                        service.Start();
                        service.WaitForStatus(ServiceControllerStatus.Running, timeout);
                    }
                }
                catch (Exception e)
                {
                    if (e.Message.Contains("MpsSvc"))
                    {
                        throw new Exception(Messages.NetworkLockWindowsFirewallUnableToStartService);
                    }
                    else
                    {
                        throw e;
                    }
                }
                finally
                {
                    if (service != null)
                    {
                        service.Dispose();
                    }
                }
            }

            // If 'winfirewall_rules_original.airvpn' doesn't exists, create it. It's a general backup of the first time.
            // We create this kind of file in Windows System directory, because it's system critical data, and to allow it to survive between re-installation of the software.
            string rulesBackupFirstTime = Engine.Instance.Storage.GetPathInData("winfirewall_rules_original.wfw");

            if (Platform.Instance.FileExists(rulesBackupFirstTime) == false)
            {
                SystemShell.ShellCmd("netsh advfirewall export \"" + SystemShell.EscapePath(rulesBackupFirstTime) + "\"");
            }

            string rulesBackupSession = Engine.Instance.Storage.GetPathInData("winfirewall_rules_backup.wfw");

            if (Platform.Instance.FileExists(rulesBackupSession))
            {
                Platform.Instance.FileDelete(rulesBackupSession);
            }
            SystemShell.ShellCmd("netsh advfirewall export \"" + SystemShell.EscapePath(rulesBackupSession) + "\"");
            if (Platform.Instance.FileExists(rulesBackupSession) == false)
            {
                throw new Exception(Messages.NetworkLockWindowsFirewallBackupFailed);
            }

            foreach (NetworkLockWindowsFirewallProfile profile in Profiles)
            {
                profile.Fetch();
            }

            foreach (NetworkLockWindowsFirewallProfile profile in Profiles)
            {
                if (profile.State == false)
                {
                    profile.StateOn();
                }

                /*
                 * if (profile.Notifications == true)
                 * {
                 *      profile.NotifyOff();
                 * }
                 */
            }

            // Disable all notifications
            SystemShell.ShellCmd("netsh advfirewall set allprofiles settings inboundusernotification disable");

            SystemShell.ShellCmd("netsh advfirewall firewall delete rule name=all");

            // Windows Firewall don't work with logical path (a path that contain hardlink)
            SystemShell.ShellCmd("netsh advfirewall firewall add rule name=\"Eddie - Out - Program Eddie\" dir=out action=allow program=\"" + SystemShell.EscapePath(Platform.Instance.FileGetPhysicalPath(Platform.Instance.GetExecutablePath())) + "\" enable=yes");

            // Adding rules are slow, so force at least curl
            SystemShell.ShellCmd("netsh advfirewall firewall add rule name=\"Eddie - Out - Program curl\" dir=out action=allow program=\"" + SystemShell.EscapePath(Platform.Instance.FileGetPhysicalPath(Software.GetTool("curl").Path)) + "\" enable=yes");

            if (Engine.Instance.Storage.GetBool("netlock.allow_ping") == true)
            {
                SystemShell.ShellCmd("netsh advfirewall firewall add rule name=\"Eddie - In - ICMP IPv4\" dir=in action=allow protocol=icmpv4:8,any");
                SystemShell.ShellCmd("netsh advfirewall firewall add rule name=\"Eddie - In - ICMP IPv6\" dir=in action=allow protocol=icmpv6:8,any");
                SystemShell.ShellCmd("netsh advfirewall firewall add rule name=\"Eddie - Out - ICMP IPv4\" dir=out action=allow protocol=icmpv4:8,any");
                SystemShell.ShellCmd("netsh advfirewall firewall add rule name=\"Eddie - Out - ICMP IPv6\" dir=out action=allow protocol=icmpv6:8,any");
            }

            // Exec("netsh advfirewall firewall add rule name=\"Eddie - IPv6 Block - Low\" dir=out remoteip=0000::/1 action=allow");
            // Exec("netsh advfirewall firewall add rule name=\"Eddie - IPv6 Block - High\" dir=out remoteip=8000::/1 action=allow");

            if (Engine.Instance.Storage.GetBool("netlock.allow_private") == true)
            {
                SystemShell.ShellCmd("netsh advfirewall firewall add rule name=\"Eddie - In - AllowLocal\" dir=in action=allow remoteip=LocalSubnet");
                SystemShell.ShellCmd("netsh advfirewall firewall add rule name=\"Eddie - Out - AllowLocal\" dir=out action=allow remoteip=LocalSubnet");

                SystemShell.ShellCmd("netsh advfirewall firewall add rule name=\"Eddie - Out - AllowMulticast\" dir=out action=allow remoteip=224.0.0.0/24");
                SystemShell.ShellCmd("netsh advfirewall firewall add rule name=\"Eddie - Out - AllowSimpleServiceDiscoveryProtocol\" dir=out action=allow remoteip=239.255.255.250/32");
                SystemShell.ShellCmd("netsh advfirewall firewall add rule name=\"Eddie - Out - ServiceLocationProtocol\" dir=out action=allow remoteip=239.255.255.253/32");
            }

            // This is not optimal, it maybe also allow LAN traffic, but we can't find a better alternative (interfacetype=ras don't work) and WinFirewall method must be deprecated.
            SystemShell.ShellCmd("netsh advfirewall firewall add rule name=\"Eddie - In - AllowVPN\" dir=in action=allow localip=10.0.0.0/8");
            SystemShell.ShellCmd("netsh advfirewall firewall add rule name=\"Eddie - Out - AllowVPN\" dir=out action=allow localip=10.0.0.0/8");

            // Without this, Windows stay in 'Identifying network...' and OpenVPN in 'Waiting TUN to come up'.
            SystemShell.ShellCmd("netsh advfirewall firewall add rule name=\"Eddie - Out - DHCP\" dir=out action=allow protocol=UDP localport=68 remoteport=67 program=\"%SystemRoot%\\system32\\svchost.exe\" service=\"dhcp\"");

            string cmd = "netsh advfirewall set allprofiles firewallpolicy ";

            if (Engine.Instance.Storage.Get("netlock.incoming") == "allow")
            {
                cmd += "allowinbound";
            }
            else
            {
                cmd += "blockinbound";
            }
            cmd += ",";
            if (Engine.Instance.Storage.Get("netlock.outgoing") == "allow")
            {
                cmd += "allowoutbound";
            }
            else
            {
                cmd += "blockoutbound";
            }
            SystemShell.ShellCmd(cmd);

            m_activated = true;             // To avoid OnUpdateIps before this moment

            OnUpdateIps();
        }
Beispiel #39
0
        // Get the title of the software
        public static string GetSoftwareTitle(Software soft)
        {
            string ret = "";

            switch (soft)
            {
                case Software.vpnbridge:
                    ret = "PacketiX VPN Bridge";
                    break;

                case Software.vpnclient:
                    ret = "PacketiX VPN Client";
                    break;

                case Software.vpnserver:
                    ret = "PacketiX VPN Server";
                    break;

                case Software.vpnserver_vpnbridge:
                    ret = "PacketiX VPN Server and VPN Bridge";
                    break;

                default:
                    throw new ApplicationException("invalid soft.");
            }

            #if BU_SOFTETHER
            ret = Str.ReplaceStr(ret, "PacketiX", "SoftEther", false);
            #endif

            return ret;
        }
Beispiel #40
0
        public static async void Initialize(ApplicationDbContext context, UserManager <IdentityUser> userManager, RoleManager <IdentityRole> roleManager)
        {
            context.Database.EnsureCreated();

            // Look for any data, abort seed if found
            if (context.Locations.Any() ||
                context.Rooms.Any() ||
                context.Hardwares.Any() ||
                context.Owners.Any() ||
                context.Softwares.Any() ||
                context.Brands.Any() ||
                context.HW_SW.Any())
            {
                return;
            }


            var locations = new Location[]
            {
                new Location {
                    Address = "Kopilica 7", Place = "Split", Country = "Croatia"
                },
                new Location {
                    Address = "Antuna Mihanovića 17", Place = "Zagreb", Country = "Croatia"
                },
                new Location {
                    Address = "Svetog leopolda Bogdana Madića 42", Place = "Osijek", Country = "Croatia"
                }
            };

            foreach (var location in locations)
            {
                context.Locations.Add(location);
            }
            context.SaveChanges();


            var rooms = new Room[]
            {
                new Room {
                    Name = "ST01", Purpose = "IT laboratorij", Floor = 0, Size = 50, LocationId = 1
                },
                new Room {
                    Name = "ST02", Purpose = "Laboratorij za elektroniku", Floor = 0, Size = 35, LocationId = 1
                },
                new Room {
                    Name = "ST03", Purpose = "Laboratorij za elektroniku", Floor = 0, Size = 35, LocationId = 1
                },
                new Room {
                    Name = "ST04", Floor = 0, Size = 70, LocationId = 1
                },
                new Room {
                    Name = "ST11", Floor = 1, Size = 70, LocationId = 1, Purpose = "Laboratorij za sve studije"
                },
                new Room {
                    Name = "ZG01", Purpose = "IT laboratorij", Floor = 0, Size = 50, LocationId = 1
                },
                new Room {
                    Name = "ZG02", Purpose = "Laboratorij za elektroniku", Floor = 0, Size = 35, LocationId = 1
                },
                new Room {
                    Name = "ZG03", Purpose = "Laboratorij za elektroniku", Floor = 0, Size = 35, LocationId = 1
                },
                new Room {
                    Name = "ZG04", Floor = 0, Size = 70, LocationId = 1
                },
                new Room {
                    Name = "ZG11", Floor = 1, Size = 70, LocationId = 1, Purpose = "Laboratorij za sve studije"
                }
            };

            foreach (var room in rooms)
            {
                context.Rooms.Add(room);
            }
            context.SaveChanges();

            var brands = new Brand[]
            {
                new Brand {
                    Name = "Microsoft", ContactFullName = "Adam Spencer", Email = "[email protected],", WebPage = "https://www.microsoft.com"
                },
                new Brand {
                    Name = "Adobe", ContactFullName = "Katerina Sandler", Email = "[email protected],", WebPage = "https://www.adobe.com"
                },
                new Brand {
                    Name = "Google", ContactFullName = "Phill Collins", Phone = "+235 18 523 1234", WebPage = "https://www.google.com"
                },
                new Brand {
                    Name = "Apple", ContactFullName = "Herkulies Lu", Phone = "+305 22 523 1234", WebPage = "https://www.apple.com"
                },
                new Brand {
                    Name = "Nvidia", WebPage = "https://www.nvidia.com"
                },
                new Brand {
                    Name = "ADM"
                },
                new Brand {
                    Name = "Gigabyte", Email = "[email protected],", WebPage = "https://www.gigabyte.com"
                },
                new Brand {
                    Name = "IBM", Email = "[email protected],", WebPage = "https://www.ibm.com"
                },
                new Brand {
                    Name = "Logitech", Email = "[email protected],", WebPage = "https://www.ibm.com"
                },
                new Brand {
                    Name = "Dell"
                },
                new Brand {
                    Name = "HP"
                },
                new Brand {
                    Name = "LG"
                },
            };

            foreach (var brand in brands)
            {
                context.Brands.Add(brand);
            }
            context.SaveChanges();

            var owners = new Owner[]
            {
                new Owner {
                    FullName = "Sveučilišni centar za stručne studije", Email = "*****@*****.**", Phone = "+38521346886"
                },
                new Owner {
                    FullName = "Sveučilište u Splitu",
                },
            };

            foreach (var owner in owners)
            {
                context.Owners.Add(owner);
            }
            context.SaveChanges();

            var softwares = new Software[]
            {
                new Software {
                    BrandId = 1, LicenceType = LicenceType.Proprietary, Name = "Visual Studio", Purpose = "Za progamiranje u C#, web development, C/C++"
                },
                new Software {
                    BrandId = 3, LicenceType = LicenceType.Protective, Name = "Google drive"
                },
                new Software {
                    LicenceType = LicenceType.Protective, Name = "Statictica"
                },
                new Software {
                    BrandId = 1, LicenceType = LicenceType.Proprietary, Name = "Windows"
                },
                new Software {
                    BrandId = 1, LicenceType = LicenceType.Proprietary, Name = "Office"
                },
                new Software {
                    BrandId = 1, LicenceType = LicenceType.Proprietary, Name = "Azure"
                },
                new Software {
                    LicenceType = LicenceType.PublicDomain, Name = "Linux Ubuntu"
                },
                new Software {
                    LicenceType = LicenceType.PublicDomain, Name = "Notepad++"
                },
            };

            foreach (var software in softwares)
            {
                context.Softwares.Add(software);
            }
            context.SaveChanges();

            var hardwares = new Hardware[]
            {
                new Hardware {
                    RoomId = 1, Name = "Monitor-17-01", Specs = "17\"", Condition = Condition.Poor, BrandId = 12, AcquiredDate = DateTime.Parse("2015-09-01"), Serial = "SDUIH3289D", OwnerId = 1
                },
                new Hardware {
                    RoomId = 1, Name = "Monitor-24-01", Specs = "24\"", Condition = Condition.Excelent, BrandId = 12, AcquiredDate = DateTime.Parse("2018-09-01"), Serial = "S123DUADSFIH3289D", OwnerId = 1
                },
                new Hardware {
                    RoomId = 1, Name = "Monitor-18-01", Specs = "18\"", Condition = Condition.Excelent, BrandId = 12, AcquiredDate = DateTime.Parse("2017-10-01"), Serial = "S123DSFIH3289D", OwnerId = 1
                },
                new Hardware {
                    RoomId = 1, Name = "PC01", Specs = "Intel i7, Nvidia 1060", Condition = Condition.Excelent, BrandId = 10, AcquiredDate = DateTime.Parse("2017-10-01"), Serial = "S123DSFIH3289D", OwnerId = 1
                },
                new Hardware {
                    RoomId = 1, Name = "PC02", Specs = "Intel i7, Nvidia 1060", Condition = Condition.Excelent, BrandId = 10, AcquiredDate = DateTime.Parse("2017-10-01"), Serial = "S123DSFIH3289D", OwnerId = 1
                },
                new Hardware {
                    RoomId = 1, Name = "PC03", Specs = "Intel i7, Nvidia 1060", Condition = Condition.Excelent, BrandId = 10, AcquiredDate = DateTime.Parse("2017-10-01"), Serial = "S123DSFIH3289D", OwnerId = 1
                },

                new Hardware {
                    RoomId = 2, Name = "Monitor-17-02", Specs = "17\"", Condition = Condition.Poor, BrandId = 12, AcquiredDate = DateTime.Parse("2015-09-01"), Serial = "SDUIH3289D", OwnerId = 1
                },
                new Hardware {
                    RoomId = 2, Name = "Monitor-24-02", Specs = "24\"", Condition = Condition.Excelent, BrandId = 12, AcquiredDate = DateTime.Parse("2018-09-01"), Serial = "S123DUADSFIH3289D", OwnerId = 1
                },
                new Hardware {
                    RoomId = 2, Name = "Monitor-18-02", Specs = "18\"", Condition = Condition.Excelent, BrandId = 12, AcquiredDate = DateTime.Parse("2017-10-01"), Serial = "S123DSFIH3289D", OwnerId = 1
                },
                new Hardware {
                    RoomId = 2, Name = "PC04", Specs = "Intel i7, Nvidia 1060", Condition = Condition.Excelent, BrandId = 10, AcquiredDate = DateTime.Parse("2017-10-01"), Serial = "S123DSFIH3289D", OwnerId = 1
                },
                new Hardware {
                    RoomId = 2, Name = "PC05", Specs = "Intel i7, Nvidia 1060", Condition = Condition.Excelent, BrandId = 10, AcquiredDate = DateTime.Parse("2017-10-01"), Serial = "S123DSFIH3289D", OwnerId = 1
                },
                new Hardware {
                    RoomId = 2, Name = "PC06", Specs = "Intel i7, Nvidia 1060", Condition = Condition.Excelent, BrandId = 10, AcquiredDate = DateTime.Parse("2017-10-01"), Serial = "S123DSFIH3289D", OwnerId = 1
                },
            };

            foreach (var hardware in hardwares)
            {
                context.Hardwares.Add(hardware);
            }
            context.SaveChanges();

            var hw_sws = new HW_SW[]
            {
                new HW_SW {
                    HardwareId = 4, SoftwareId = 4, Version = "10.0.1234", Status = Status.Active
                },
                new HW_SW {
                    HardwareId = 4, SoftwareId = 5, Version = "19.0.123", Status = Status.Active
                },
                new HW_SW {
                    HardwareId = 4, SoftwareId = 1, Version = "19.0.3", Status = Status.Active
                },
                new HW_SW {
                    HardwareId = 5, SoftwareId = 4, Version = "10.0.1234", Status = Status.Active
                },
                new HW_SW {
                    HardwareId = 5, SoftwareId = 5, Version = "19.0.123", Status = Status.Active
                },
                new HW_SW {
                    HardwareId = 5, SoftwareId = 1, Version = "19.0.3", Status = Status.Active
                },
                new HW_SW {
                    HardwareId = 5, SoftwareId = 8, Version = "10.0.1234", Status = Status.Active
                },
                new HW_SW {
                    HardwareId = 6, SoftwareId = 4, Version = "12.0.1234", Status = Status.Active
                },
                new HW_SW {
                    HardwareId = 6, SoftwareId = 5, Version = "44.0.123", Status = Status.Active
                },
                new HW_SW {
                    HardwareId = 6, SoftwareId = 1, Version = "23.0.3", Status = Status.Active
                },
                new HW_SW {
                    HardwareId = 10, SoftwareId = 8, Version = "3.0.123", Status = Status.Active
                },
                new HW_SW {
                    HardwareId = 11, SoftwareId = 8, Version = "3.0.3", Status = Status.Active
                },
            };

            foreach (var hw_sw in hw_sws)
            {
                context.HW_SW.Add(hw_sw);
            }
            context.SaveChanges();

            var roles = new IdentityRole[]
            {
                new IdentityRole {
                    Name = "Admin", NormalizedName = "ADMIN"
                },
                new IdentityRole {
                    Name = "PowerUser", NormalizedName = "POWERUSER"
                },
                new IdentityRole {
                    Name = "User", NormalizedName = "USER"
                },
            };

            foreach (var role in roles)
            {
                roleManager.CreateAsync(role).Wait();
            }

            var user = new IdentityUser
            {
                UserName       = "******",
                Email          = "*****@*****.**",
                EmailConfirmed = true
            };

            userManager.CreateAsync(user, "Opatija-1").Wait();
            userManager.AddToRoleAsync(user, "Admin").Wait();

            user = new IdentityUser
            {
                UserName       = "******",
                Email          = "*****@*****.**",
                EmailConfirmed = true
            };
            userManager.CreateAsync(user, "Opatija-1").Wait();
            userManager.AddToRoleAsync(user, "PowerUser").Wait();

            user = new IdentityUser
            {
                UserName       = "******",
                Email          = "*****@*****.**",
                EmailConfirmed = true
            };

            userManager.CreateAsync(user, "Opatija-1").Wait();
            userManager.AddToRoleAsync(user, "User").Wait();

            // /*DEAD CODE BELOW*/
            // var users = new IdentityUser[]
            // {
            //     new IdentityUser{ Id="1", Email="*****@*****.**", UserName="******", NormalizedUserName="******", PhoneNumber="+3852345123", NormalizedEmail="*****@*****.**".ToUpper()},
            //     new IdentityUser{ Id="2", Email="*****@*****.**", UserName="******", NormalizedUserName="******", PhoneNumber="+3852345123", NormalizedEmail="*****@*****.**".ToUpper()},
            //     new IdentityUser{ Id="3", Email="*****@*****.**", UserName="******", NormalizedUserName="******", PhoneNumber="+3852345123", NormalizedEmail="*****@*****.**".ToUpper()},
            // };

            // //var user = new IdentityUser();
            // //user.UserName = "******";
            // //user.Email = "*****@*****.**";

            // //string userPWD = "somepassword";

            // //IdentityResult chkUser = await userManager.CreateAsync(user, userPWD).;

            // foreach (var user in users)
            // {
            //     userManager.CreateAsync(user, "Opatija 1").Wait();
            //     //userManager.AddToRoleAsync(user, "Admin").Wait();
            //     context.Users.Add(user);
            // }
            // context.SaveChanges();
        }
        //==================== search orders

        public static List <Order> SearchRecord_orders(string name)
        {
            List <Order> orders = new List <Order>();

            if (File.Exists(myPath_Order))
            {
                StreamReader sReader = new StreamReader(myPath_Order);
                string       line    = sReader.ReadLine();

                while (line != null)
                {
                    Order    order             = new Order();
                    string[] currentLineFields = line.Split(',');
                    if ((currentLineFields[0].Equals(name)) || (currentLineFields[1].Equals(name)) || (currentLineFields[2].Equals(name)) ||
                        (currentLineFields[3].Equals(name)))
                    {
                        if (currentLineFields[9] == "software")
                        {
                            Order    o    = new Order();
                            Software soft = new Software();
                            Client   c    = new Client();

                            o.OrderId        = Convert.ToDouble(currentLineFields[0]);
                            soft.ProductID   = currentLineFields[1];
                            soft.ProductName = currentLineFields[2];
                            soft.UnitPrice   = Convert.ToDouble(currentLineFields[4]);

                            c.Name = currentLineFields[3];

                            o.Amount = Convert.ToDouble(currentLineFields[5]);

                            o.RequiredDate = Convert.ToDateTime(currentLineFields[6]);
                            o.ShippingDate = Convert.ToDateTime(currentLineFields[7]);
                            o.Total1       = Convert.ToDouble(currentLineFields[8]);
                            o.TitleOrder   = currentLineFields[9];
                            o.Status       = currentLineFields[10];
                            o.Software     = soft;
                            o.Client       = c;
                            orders.Add(o);
                        }
                        else if (currentLineFields[9] == "book")
                        {
                            Order  o    = new Order();
                            Book   book = new Book();
                            Client c    = new Client();
                            o.OrderId        = Convert.ToDouble(currentLineFields[0]);
                            book.ProductID   = currentLineFields[1];
                            book.ProductName = currentLineFields[2];
                            book.UnitPrice   = Convert.ToDouble(currentLineFields[4]);

                            c.Name = currentLineFields[3];

                            o.Amount = Convert.ToDouble(currentLineFields[5]);

                            o.RequiredDate = Convert.ToDateTime(currentLineFields[6]);
                            o.ShippingDate = Convert.ToDateTime(currentLineFields[7]);
                            o.Total1       = Convert.ToDouble(currentLineFields[8]);
                            o.TitleOrder   = currentLineFields[9];

                            o.Status = currentLineFields[10];
                            o.Book   = book;
                            o.Client = c;
                            orders.Add(o);
                        }
                    }

                    line = sReader.ReadLine();
                }

                sReader.Close();
                return(orders);
            }
            else
            {
                MessageBox.Show("Data Not Found!");
                return(null);
            }
        }
        /// <summary>
        /// Return the list of locally installed softwares on the computer
        /// </summary>
        /// <param name="computer">The computer to use</param>
        /// <returns>A list of all the installed softwares</returns>
        public static async Task <IEnumerable <Software> > getInstalledSoftwares(Computer computer, int architecture)
        {
            const string softwareRegLoc     = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
            const uint   HKEY_LOCAL_MACHINE = 0x80000002;

            string[] valueNames = { "DisplayName", "DisplayVersion", "InstallDate", "Publisher", "Comment", "ReleaseType", "SystemComponent", "ParentDisplayName", "InstallLocation" };

            // Perform the operation asynchronously
            return(await Task.Run(() => {
                try {
                    List <Software> installedSoftwares = new List <Software>();

                    // Create the scope
                    var wmiScope = new ManagementScope($@"\\{computer.nameLong}\root\cimv2", getConnectionOptions());
                    wmiScope.Options.Context.Add("__ProviderArchitecture", architecture);
                    wmiScope.Options.Context.Add("__RequiredArchitecture", true);
                    wmiScope.Connect();

                    // Get the WMI process
                    var wmiProcess = new ManagementClass(wmiScope, new ManagementPath("StdRegProv"), null);

                    // First request to get all the subkeys
                    ManagementBaseObject inParams = wmiProcess.GetMethodParameters("EnumKey");
                    inParams["hDefKey"] = HKEY_LOCAL_MACHINE;
                    inParams["sSubKeyName"] = softwareRegLoc;

                    // Read Registry Key Names
                    ManagementBaseObject outParams = wmiProcess.InvokeMethod("EnumKey", inParams, null);
                    string[] programGuids = outParams["sNames"] as string[];

                    // For each subkey
                    foreach (string subKeyName in programGuids)
                    {
                        Dictionary <string, string> values = new Dictionary <string, string>();
                        foreach (string valueName in valueNames)
                        {
                            inParams = wmiProcess.GetMethodParameters("GetStringValue");
                            inParams["hDefKey"] = HKEY_LOCAL_MACHINE;
                            inParams["sSubKeyName"] = $@"{softwareRegLoc}\{subKeyName}";
                            inParams["sValueName"] = valueName;
                            // Read Registry Value
                            outParams = wmiProcess.InvokeMethod("GetStringValue", inParams, null);

                            if (outParams.Properties["sValue"].Value != null)
                            {
                                values[valueName] = outParams.Properties["sValue"].Value.ToString();
                            }
                        }

                        if (!string.IsNullOrEmpty(values.GetValueOrDefault("DisplayName")) &&
                            string.IsNullOrEmpty(values.GetValueOrDefault("ReleaseType")) &&
                            string.IsNullOrEmpty(values.GetValueOrDefault("ParentDisplayName")))
                        {
                            var software = new Software()
                            {
                                displayName = values.GetValueOrDefault("DisplayName"),
                                displayVersion = values.GetValueOrDefault("DisplayVersion"),
                                publisher = values.GetValueOrDefault("Publisher"),
                                comment = values.GetValueOrDefault("Comment"),
                                installLocation = values.GetValueOrDefault("InstallLocation")
                            };

                            var installDate = values.GetValueOrDefault("InstallDate");
                            try {
                                if (installDate != null)
                                {
                                    software.installDate = DateTime.ParseExact(installDate, "yyyyMMdd", CultureInfo.InvariantCulture);
                                }
                            } catch (Exception) {
                                // Ignore invalid dates
                            }

                            installedSoftwares.Add(software);
                        }
                    }

                    return installedSoftwares;
                } catch (Exception e) {
                    throw new WMIException()
                    {
                        error = e, computer = computer.nameLong
                    };
                }
            }));
        }
Beispiel #43
0
        public void OrderToOrderDtoAdapter()
        {
            //Arrange

            var customer = new Customer();

            customer.GenerateNewIdentity();
            customer.FirstName = "Unai";
            customer.LastName  = "Zorrilla";

            Product product = new Software("the product title", "the product description", "license code");

            product.GenerateNewIdentity();

            var order = new Order();

            order.GenerateNewIdentity();
            order.OrderDate           = DateTime.Now;
            order.ShippingInformation = new ShippingInfo(
                "shippingName",
                "shippingAddress",
                "shippingCity",
                "shippingZipCode");
            order.SetTheCustomerForThisOrder(customer);

            var orderLine = order.AddNewOrderLine(product.Id, 10, 10, 0.5M);

            orderLine.SetProduct(product);

            //Act
            var adapter  = TypeAdapterFactory.CreateAdapter();
            var orderDto = adapter.Adapt <Order, OrderDto>(order);

            //Assert
            Assert.AreEqual(orderDto.Id, order.Id);
            Assert.AreEqual(orderDto.OrderDate, order.OrderDate);
            Assert.AreEqual(orderDto.DeliveryDate, order.DeliveryDate);

            Assert.AreEqual(orderDto.ShippingAddress, order.ShippingInformation.ShippingAddress);
            Assert.AreEqual(orderDto.ShippingCity, order.ShippingInformation.ShippingCity);
            Assert.AreEqual(orderDto.ShippingName, order.ShippingInformation.ShippingName);
            Assert.AreEqual(orderDto.ShippingZipCode, order.ShippingInformation.ShippingZipCode);

            Assert.AreEqual(orderDto.CustomerFullName, order.Customer.FullName);
            Assert.AreEqual(orderDto.CustomerId, order.Customer.Id);

            Assert.AreEqual(
                orderDto.OrderNumber,
                string.Format("{0}/{1}-{2}", order.OrderDate.Year, order.OrderDate.Month, order.SequenceNumberOrder));

            Assert.IsNotNull(orderDto.OrderLines);
            Assert.IsTrue(orderDto.OrderLines.Any());

            Assert.AreEqual(orderDto.OrderLines[0].Id, orderLine.Id);
            Assert.AreEqual(orderDto.OrderLines[0].Amount, orderLine.Amount);
            Assert.AreEqual(orderDto.OrderLines[0].Discount, orderLine.Discount * 100);
            Assert.AreEqual(orderDto.OrderLines[0].UnitPrice, orderLine.UnitPrice);
            Assert.AreEqual(orderDto.OrderLines[0].TotalLine, orderLine.TotalLine);
            Assert.AreEqual(orderDto.OrderLines[0].ProductId, product.Id);
            Assert.AreEqual(orderDto.OrderLines[0].ProductTitle, product.Title);
        }
 public SoftwareBuilder()
 {
     Software = new Software();
 }
Beispiel #45
0
 public void RegisterSoftware(Software s)
 {
     this.capacityInUse += s.CapacityConsumption;
     this.memoryInUse += s.MemoryConsumption;
     this.software.Add(s);
 }
Beispiel #46
0
 private void Software(object sender, RoutedEventArgs e)
 {
     DataContext = new Software(login);
 }
 public SoftwareControl(Software software) : this()
 {
     this.software = software;
     lblName.Text = software.Name;
     toolTip1.SetToolTip(lblName, lblName.Text);
 }
Beispiel #48
0
        private void btnModify_Click(object sender, EventArgs e)
        {
            Product prod     = null;
            int     temp_seq = 0;

            try
            {
                if (cmbTypeProd.Text == "Book")
                {
                    if (!DataValidator.verifyData(txtBPages.Text, new Regex(DataValidator.patternNumber)))
                    {
                        MessageBox.Show("Pages must be a numeric value", "Error",
                                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    prod = new Book(Convert.ToInt16(txtBPages.Text),
                                    (EnumBookGenre)cmbBGenre.SelectedItem);
                    temp_seq = prod.Item; //Store last sequence
                }
                else if (cmbTypeProd.Text == "Software")
                {
                    if (!DataValidator.verifyData(txtSCapacity.Text, new Regex(DataValidator.patternNumber)))
                    {
                        MessageBox.Show("Software Capacity has to be a numeric value", "Error",
                                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    prod     = new Software(txtSCapacity.Text, (EnumSoftType)cmbSoftType.SelectedItem);
                    temp_seq = prod.Item; //Store last sequence
                }
                else
                {
                    MessageBox.Show("Must be selected an Employee's Category...", "Error",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                try
                {
                    prod.SerialNumber = txtSN.Text;
                    prod.Type         = (EnumProdType)cmbTypeProd.SelectedItem;
                    prod.Titname      = txtTitle.Text;
                    prod.Author       = txtAuthor.Text;

                    // Validating Price
                    if (!DataValidator.verifyData(txtPrice.Text, new Regex(DataValidator.patternMoney)))
                    {
                        MessageBox.Show("Price has to be a numeric value", "Error",
                                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    prod.Price = Convert.ToDouble(txtPrice.Text);

                    //Validating Date
                    if (!DataValidator.verifyData(txtHDay.Text, new Regex(DataValidator.patternDay)))
                    {
                        MessageBox.Show("Wrong day...Must be between 1 and 31", "Error",
                                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                        SequenceID.setProd_id(temp_seq); // Decrease the sequence
                        return;
                    }
                    if (!DataValidator.verifyData(txtHMonth.Text, new Regex(DataValidator.patternMonth)))
                    {
                        MessageBox.Show("Wrong month...Must be between 1 and 12", "Error",
                                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                        SequenceID.setProd_id(temp_seq); // Decrease the sequence
                        return;
                    }
                    if (!DataValidator.verifyData(txtHYear.Text, new Regex(DataValidator.patternYear)))
                    {
                        MessageBox.Show("Wrong year...Must be between 1900 and 2099", "Error",
                                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                        SequenceID.setProd_id(temp_seq); // Decrease the sequence
                        return;
                    }
                    prod.Ed_pubDate = new Date(txtHDay.Text, txtHMonth.Text, txtHYear.Text);

                    // Validating Stock
                    if (!DataValidator.verifyData(txtStock.Text, new Regex(DataValidator.patternNumber)))
                    {
                        MessageBox.Show("Stock has to be a numeric value", "Error",
                                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    prod.Stock = Convert.ToInt16(txtStock.Text);

                    prod.SerialNumber = tempsn; //Assign last displayed SN

                    prod.Item = temp_id;

                    if (txtSN.Text != prod.SerialNumber)
                    {
                        MessageBox.Show("Can't to modify the SN in the Modify option.  It should use Add button",
                                        "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    if (update_index > -1)
                    {
                        // Update list Box and list of Products
                        product_list.modify(prod, prod.SerialNumber);
                        listBoxProducts.Items.Clear();
                        foreach (Product temp in product_list.ReturnList())
                        {
                            this.listBoxProducts.Items.Add(product_list.ShowListInBox(temp));
                        }

                        btnReset.PerformClick();

                        update_index = -1;

                        save_flag = true;

                        MessageBox.Show("Product Mofified", "Confirmation",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show("It must to select an item and display it.  Use Display Option",
                                        "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                catch
                {
                    MessageBox.Show("Missing or incorrects values to enter...Check and Try again",
                                    "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch
            {
                MessageBox.Show("Missing or incorrects values to enter...Check and Try again",
                                "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
		public BuildSoftwareWin32(Software software, int buildNumber, int version, string buildName, Cpu cpu, OS os)
			: base(software, buildNumber, version, buildName, cpu, os)
		{
		}
Beispiel #50
0
        private void btnAdd_Click(object sender, EventArgs e)
        {
            Product prod     = null;
            int     temp_seq = 0;

            if (!product_list.isUnique(txtSN.Text))
            {
                MessageBox.Show("There is another product with this SN...",
                                "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (cmbTypeProd.Text == "Book")
            {
                if (!DataValidator.verifyData(txtBPages.Text, new Regex(DataValidator.patternNumber)))
                {
                    MessageBox.Show("Pages has to be a numeric value", "Error",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                prod = new Book(Convert.ToInt16(txtBPages.Text),
                                (EnumBookGenre)cmbBGenre.SelectedItem);
                temp_seq = prod.Item; //Store last sequence
            }
            else if (cmbTypeProd.Text == "Software")
            {
                if (!DataValidator.verifyData(txtSCapacity.Text, new Regex(DataValidator.patternNumber)))
                {
                    MessageBox.Show("Software Capacity has to be a numeric value", "Error",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                prod     = new Software(txtSCapacity.Text, (EnumSoftType)cmbSoftType.SelectedItem);
                temp_seq = prod.Item; //Store last sequence
            }
            else
            {
                MessageBox.Show("Must be select a Type of Product...", "Error",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            try
            {
                prod.SerialNumber = txtSN.Text;
                prod.Type         = (EnumProdType)cmbTypeProd.SelectedItem;
                prod.Titname      = txtTitle.Text;
                prod.Author       = txtAuthor.Text;

                // Validating Price
                if (!DataValidator.verifyData(txtPrice.Text, new Regex(DataValidator.patternMoney)))
                {
                    MessageBox.Show("Price has to be a numeric value", "Error",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                prod.Price = Convert.ToDouble(txtPrice.Text);

                //Validating Date
                if (!DataValidator.verifyData(txtHDay.Text, new Regex(DataValidator.patternDay)))
                {
                    MessageBox.Show("Wrong day...Must be between 1 and 31", "Error",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                    SequenceID.setProd_id(temp_seq); // Decrease the sequence
                    return;
                }
                if (!DataValidator.verifyData(txtHMonth.Text, new Regex(DataValidator.patternMonth)))
                {
                    MessageBox.Show("Wrong month...Must be between 1 and 12", "Error",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                    SequenceID.setProd_id(temp_seq); // Decrease the sequence
                    return;
                }
                if (!DataValidator.verifyData(txtHYear.Text, new Regex(DataValidator.patternYear)))
                {
                    MessageBox.Show("Wrong year...Must be between 1900 and 2099", "Error",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                    SequenceID.setProd_id(temp_seq); // Decrease the sequence
                    return;
                }
                prod.Ed_pubDate = new Date(txtHDay.Text, txtHMonth.Text, txtHYear.Text);

                // Validating Stock
                if (!DataValidator.verifyData(txtStock.Text, new Regex(DataValidator.patternNumber)))
                {
                    MessageBox.Show("Stock has to be a numeric value", "Error",
                                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                prod.Stock = Convert.ToInt16(txtStock.Text);

                // Adding to list
                product_list.add(prod);

                this.listBoxProducts.Items.Add(product_list.ShowListInBox(prod));
                btnReset.PerformClick();

                MessageBox.Show("Product Added", "Confirmation",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
                save_flag = true;
            }
            catch
            {
                MessageBox.Show("Missing or incorrects values to enter...Check and Try again",
                                "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        public BuildSoftwareUnix(Software software, int buildNumber, int version, string buildName, Cpu cpu, OS os, 
            string crossLibName, bool useGccBitsOption, string crossCompilerName, bool noPthreadOption, string crossCompilerOption)
            : base(software, buildNumber, version, buildName, cpu, os)
        {
            this.CrossLibName = crossLibName;
            this.UseGccBitsOption = useGccBitsOption;
            this.CrossCompilerName = crossCompilerName;
            this.NoPThreadOption = noPthreadOption;
            this.CrossCompilerOption = crossCompilerOption;

            #if !BU_SOFTETHER
            this.SrcKitDefaultDir = Env.SystemDir.Substring(0, 2) + @"\tmp\vpn4_srckit";
            #else
            this.SrcKitDefaultDir = Env.SystemDir.Substring(0, 2) + @"\tmp\se_vpn_srckit";
            #endif
        }
Beispiel #52
0
        public byte[] FetchUrlEx(string url, System.Collections.Specialized.NameValueCollection parameters, string title, bool forceBypassProxy, string resolve)
        {
            if (Available() == false)
            {
                throw new Exception(Messages.ToolsCurlRequired);
            }

            if (Utils.CompareVersions(Version, minVersionRequired) == -1)
            {
                throw new Exception(GetRequiredVersionMessage());
            }

            ProgramScope programScope = new ProgramScope(this.GetPath(), "curl");

            // Don't use proxy if connected to the VPN, or in special cases (checking) during connection.
            bool bypassProxy = forceBypassProxy;

            if (bypassProxy == false)
            {
                bypassProxy = Engine.Instance.IsConnected();
            }

            string dataParameters = "";

            if (parameters != null)
            {
                foreach (string k in parameters.Keys)
                {
                    if (dataParameters != "")
                    {
                        dataParameters += "&";
                    }
                    dataParameters += SystemShell.EscapeAlphaNumeric(k) + "=" + Uri.EscapeUriString(parameters[k]);
                }
            }

            string args = "";

            if (bypassProxy == false)
            {
                string proxyMode     = Engine.Instance.Storage.Get("proxy.mode").ToLowerInvariant();
                string proxyHost     = Engine.Instance.Storage.Get("proxy.host");
                int    proxyPort     = Engine.Instance.Storage.GetInt("proxy.port");
                string proxyAuth     = Engine.Instance.Storage.Get("proxy.auth").ToLowerInvariant();
                string proxyLogin    = Engine.Instance.Storage.Get("proxy.login");
                string proxyPassword = Engine.Instance.Storage.Get("proxy.password");

                if (proxyMode == "detect")
                {
                    throw new Exception(Messages.ProxyDetectDeprecated);
                }

                if (proxyMode == "tor")
                {
                    proxyMode     = "socks";
                    proxyAuth     = "none";
                    proxyLogin    = "";
                    proxyPassword = "";
                }

                if (proxyMode == "http")
                {
                    args += " --proxy http://" + SystemShell.EscapeHost(proxyHost) + ":" + proxyPort.ToString();
                }
                else if (proxyMode == "socks")
                {
                    // curl support different types of proxy. OpenVPN not, only socks5. So, it's useless to support other kind of proxy here.
                    args += " --proxy socks5://" + SystemShell.EscapeHost(proxyHost) + ":" + proxyPort.ToString();
                }

                if ((proxyMode != "none") && (proxyAuth != "none"))
                {
                    if (proxyAuth == "basic")
                    {
                        args += " --proxy-basic";
                    }
                    else if (proxyAuth == "ntlm")
                    {
                        args += " --proxy-ntlm";
                    }

                    if (SystemShell.EscapeInsideQuoteAcceptable(proxyLogin) == false)
                    {
                        throw new Exception(MessagesFormatter.Format(Messages.UnacceptableCharacters, "Proxy Login"));
                    }

                    if (SystemShell.EscapeInsideQuoteAcceptable(proxyPassword) == false)
                    {
                        throw new Exception(MessagesFormatter.Format(Messages.UnacceptableCharacters, "Proxy Password"));
                    }

                    if ((proxyLogin != "") && (proxyPassword != ""))
                    {
                        args += " --proxy-user \"" + SystemShell.EscapeInsideQuote(proxyLogin) + "\":\"" + SystemShell.EscapeInsideQuote(proxyPassword) + "\"";
                    }
                }
            }

            args += " \"" + SystemShell.EscapeUrl(url) + "\"";
            args += " -sS"; // -s Silent mode, -S with errors
            args += " --max-time " + Engine.Instance.Storage.GetInt("tools.curl.max-time").ToString();

            Tool cacertTool = Software.GetTool("cacert.pem");

            if (cacertTool.Available())
            {
                args += " --cacert \"" + SystemShell.EscapePath(cacertTool.Path) + "\"";
            }

            if (resolve != "")
            {
                args += " --resolve " + resolve;
            }

            if (dataParameters != "")
            {
                args += " --data \"" + dataParameters + "\"";
            }

            string error = "";

            byte[] output   = default(byte[]);
            int    exitcode = -1;

            try
            {
                /*
                 * if ((Engine.Instance != null) && (Engine.Instance.Storage != null) && (Engine.Instance.Storage.GetBool("log.level.debug")))
                 * {
                 *  string message = "curl " + this.GetPath() + " " + args;
                 *  message = Utils.RegExReplace(message, "[a-zA-Z0-9+/]{30,}=", "{base64-omissis}");
                 *  Engine.Instance.Logs.Log(LogType.Verbose, message);
                 * }
                 */

                Process p = new Process();

                p.StartInfo.FileName         = SystemShell.EscapePath(this.GetPath());
                p.StartInfo.Arguments        = args;
                p.StartInfo.WorkingDirectory = "";

                p.StartInfo.CreateNoWindow         = true;
                p.StartInfo.WindowStyle            = System.Diagnostics.ProcessWindowStyle.Hidden;
                p.StartInfo.UseShellExecute        = false;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.RedirectStandardError  = true;

                p.Start();

                using (var memoryStream = new System.IO.MemoryStream())
                {
                    //p.StandardOutput.BaseStream.CopyTo(memstream); // .Net 4 only
                    Utils.CopyStream(p.StandardOutput.BaseStream, memoryStream);
                    output = memoryStream.ToArray();
                }

                error = p.StandardError.ReadToEnd();

                p.WaitForExit();

                exitcode = p.ExitCode;
            }
            catch (Exception e)
            {
                error  = e.Message;
                output = default(byte[]);
            }

            programScope.End();

            if (error != "")
            {
                throw new Exception(error.Trim());
            }

            return(output);
        }