Esempio n. 1
0
 // Deletes a VPC
 private void DeleteVPC(VPC vpc)
 {
     using (var ec2 = TestBase.CreateClient <Amazon.EC2.AmazonEC2Client>())
     {
         ec2.DeleteVpcAsync(new Amazon.EC2.Model.DeleteVpcRequest
         {
             VpcId = vpc.VPCId
         }).Wait();
     }
 }
Esempio n. 2
0
 // Deletes a VPC
 private void DeleteVPC(VPC vpc)
 {
     using (var ec2 = new Amazon.EC2.AmazonEC2Client())
     {
         ec2.DeleteVpc(new Amazon.EC2.Model.DeleteVpcRequest
         {
             VpcId = vpc.VPCId
         });
     }
 }
Esempio n. 3
0
        public async Task <IActionResult> Create()
        {
            if (_context.VPCs.ToList().Count == 0)
            {
                return(RedirectToAction("", "Home", ""));
            }
            VPC vpc = await _context.VPCs.FindAsync(1);

            DescribeVpcsResponse response = await EC2Client.DescribeVpcsAsync(new DescribeVpcsRequest
            {
                Filters = new List <Filter>
                {
                    new Filter("vpc-id", new List <string>
                    {
                        vpc.AWSVPCReference
                    })
                }
            });

            String[] IPBlocks = response.Vpcs[0].CidrBlock.Split(".");
            ViewData["IPCIDR"] = IPBlocks[0] + "." + IPBlocks[1];
            return(View());
        }
Esempio n. 4
0
        public async Task DoWorkAsync()
        {
            _logger.LogInformation("Update Background Service is running");
            try
            {
                _logger.LogInformation("Update Background Service is checking VPCs");
                if (context.VPCs.Any())
                {
                    DescribeVpcsResponse responseDescribeVPC = await ec2Client.DescribeVpcsAsync();

                    List <VPC> vpcs = await context.VPCs.ToListAsync();

                    foreach (VPC vpc in vpcs)
                    {
                        Boolean Flag = false;

                        foreach (Vpc AWSVPC in responseDescribeVPC.Vpcs)
                        {
                            if (vpc.AWSVPCReference.Equals(AWSVPC.VpcId))
                            {
                                Flag = true;
                                break;
                            }
                        }
                        if (Flag == false)
                        {
                            context.VPCs.Remove(vpc);
                        }
                    }
                    context.SaveChanges();
                    _logger.LogInformation("Update Background Service completed checking of VPCs");
                }
                if (context.VPCs.Any())
                {
                    VPC vpc = await context.VPCs.FindAsync(1);

                    if (context.Servers.Any())
                    {
                        _logger.LogInformation("Update Background Service is checking servers");
                        List <Server> servers = await context.Servers.ToListAsync();

                        DescribeInstancesResponse response = await ec2Client.DescribeInstancesAsync(new DescribeInstancesRequest
                        {
                            Filters = new List <Filter>
                            {
                                new Filter {
                                    Name = "vpc-id", Values = new List <string> {
                                        vpc.AWSVPCReference
                                    }
                                }
                            }
                        });

                        foreach (var server in servers)
                        {
                            foreach (var reservation in response.Reservations)
                            {
                                foreach (var instance in reservation.Instances)
                                {
                                    bool Flag = false;
                                    if (server.AWSEC2Reference.Equals(instance.InstanceId))
                                    {
                                        if (instance.State.Code == 0 && server.State != State.Starting)
                                        {
                                            server.State = State.Starting;
                                            Flag         = true;
                                        }
                                        else if (instance.State.Code == 16 && server.State != State.Running)
                                        {
                                            server.State = State.Running;
                                            Flag         = true;
                                        }
                                        else if (instance.State.Code == 64 && server.State != State.Stopping)
                                        {
                                            server.State = State.Stopping;
                                            Flag         = true;
                                        }
                                        else if (instance.State.Code == 80 && server.State != State.Stopped)
                                        {
                                            server.State = State.Stopped;
                                            Flag         = true;
                                        }
                                        if (server.Visibility == Visibility.Internet && (server.IPAddress != instance.PublicIpAddress || server.DNSHostname != instance.PublicDnsName) && server.State != State.Stopped)
                                        {
                                            server.IPAddress   = instance.PublicIpAddress;
                                            server.DNSHostname = instance.PublicDnsName;
                                            Flag = true;
                                        }
                                        else if (server.Visibility == Visibility.Internet && (server.IPAddress != instance.PublicIpAddress || server.DNSHostname != instance.PublicDnsName))
                                        {
                                            server.IPAddress   = "Public IP Address is not available when server is stopped";
                                            server.DNSHostname = "Public DNS Hostname is not available when server is stopped";
                                            Flag = true;
                                        }
                                        else if ((server.Visibility == Visibility.Extranet || server.Visibility == Visibility.Intranet) && (server.IPAddress != instance.PrivateIpAddress || server.DNSHostname != instance.PrivateDnsName))
                                        {
                                            server.IPAddress   = instance.PrivateIpAddress;
                                            server.DNSHostname = instance.PrivateDnsName;
                                            Flag = true;
                                        }
                                        if (Flag == true)
                                        {
                                            context.Servers.Update(server);
                                        }

                                        break;
                                    }
                                }
                            }
                        }
                        context.SaveChanges();
                    }
                    if (context.CloudWatchLogGroups.Any() && context.CloudWatchLogStreams.Any())
                    {
                        _logger.LogInformation("Update Background Service is checking cloudwatch groups");
                        List <CloudWatchLogGroup> allStreams = await context.CloudWatchLogGroups.ToListAsync();

                        foreach (CloudWatchLogGroup g in allStreams)
                        {
                            DescribeLogStreamsResponse response = await cwlClient.DescribeLogStreamsAsync(new DescribeLogStreamsRequest
                            {
                                LogGroupName = g.Name.Replace("@", "/")
                            });

                            foreach (LogStream ls in response.LogStreams)
                            {
                                Boolean Flag = false;
                                foreach (CloudWatchLogStream CWLS in g.LogStreams)
                                {
                                    if (ls.Arn.Equals(CWLS.ARN))
                                    {
                                        Flag = true;
                                        break;
                                    }
                                }
                                if (Flag == false)
                                {
                                    CloudWatchLogStream newS = new CloudWatchLogStream
                                    {
                                        ARN            = ls.Arn,
                                        CreationTime   = ls.CreationTime,
                                        FirstEventTime = ls.FirstEventTimestamp,
                                        LastEventTime  = ls.LastEventTimestamp,
                                        Name           = ls.LogStreamName,
                                        LinkedGroupID  = g.ID
                                    };
                                    if (g.Name.Equals("VMVPCLogs"))
                                    {
                                        newS.DisplayName = "Network Flow Log For Challenge Network Interface (" + newS.Name.Substring(0, newS.Name.Length - 4) + ")";
                                    }
                                    else if (g.Name.Equals("PlatformVPCLogs"))
                                    {
                                        newS.DisplayName = "Network Flow Log For Platform Network Interface (" + newS.Name.Substring(0, newS.Name.Length - 4) + ")";
                                    }
                                    else if (g.Name.Equals("@aws@elasticbeanstalk@User-Side@IIS-Log"))
                                    {
                                        newS.DisplayName = "IIS Logs for User Side Web Server";
                                    }
                                    else if (g.Name.Equals("@aws@elasticbeanstalk@Admin-Side@IIS-Log"))
                                    {
                                        newS.DisplayName = "IIS Logs for Admin Side Web Server";
                                    }
                                    else if (g.Name.Equals("@aws@elasticbeanstalk@User-Side@EBDeploy-Log"))
                                    {
                                        newS.DisplayName = "Elastic Beanstalk Deployment Tool Logs for User Side";
                                    }
                                    else if (g.Name.Equals("@aws@elasticbeanstalk@Admin-Side@EBDeploy-Log"))
                                    {
                                        newS.DisplayName = "Elastic Beanstalk Deployment Tool Logs for Admin Side";
                                    }
                                    else if (g.Name.Equals("@aws@elasticbeanstalk@User-Side@EBHooks-Log"))
                                    {
                                        newS.DisplayName = "Elastic Beanstalk Deployment Hook Logs for User Side";
                                    }
                                    else if (g.Name.Equals("@aws@elasticbeanstalk@Admin-Side@EBHooks-Log"))
                                    {
                                        newS.DisplayName = "Elastic Beanstalk Deployment Hook Logs for Admin Side";
                                    }
                                    else
                                    {
                                        newS.DisplayName = newS.Name;
                                    }

                                    if (!g.Name.Equals("RDSOSMetrics") || !g.Name.Contains("sns"))
                                    {
                                        context.CloudWatchLogStreams.Add(newS);
                                    }
                                }
                            }
                            foreach (CloudWatchLogStream CWLS in g.LogStreams)
                            {
                                Boolean Flag = false;
                                foreach (LogStream ls in response.LogStreams)
                                {
                                    if (CWLS.ARN.Equals(ls.Arn))
                                    {
                                        Flag = true;
                                        break;
                                    }
                                }
                                if (Flag == false)
                                {
                                    context.CloudWatchLogStreams.Remove(CWLS);
                                }
                            }
                        }
                        await context.SaveChangesAsync();
                    }
                    if (context.Templates.Any())
                    {
                        DescribeSnapshotsResponse response = await ec2Client.DescribeSnapshotsAsync(new DescribeSnapshotsRequest());

                        List <Template> templates = await context.Templates.FromSql("SELECT * FROM dbo.Templates WHERE AWSSnapshotReference = NULL").ToListAsync();

                        foreach (Template t in templates)
                        {
                            foreach (Snapshot s in response.Snapshots)
                            {
                                if (s.Description.Contains(t.AWSAMIReference))
                                {
                                    t.AWSSnapshotReference = s.SnapshotId;
                                    break;
                                }
                            }
                        }
                        await context.SaveChangesAsync();
                    }
                }
                _logger.LogInformation("Update Background Service has completed!");
            }
            catch (SqlException e)
            {
                _logger.LogInformation("Update Background Service faced an SQL exception! " + e.Message + " | " + e.Source);
                return;
            }
            catch (Exception e)
            {
                _logger.LogInformation("Update Background Service faced an exception! " + e.Message + " | " + e.Source);
                return;
            }
        }
Esempio n. 5
0
    // Use this for initialization
    void Awake()
    {
        // Activate nodes
        foreach (string nodeName in L1Mapping.NodeNamesM1)
        {
            GNS3Handler.Instance.projectHandler.StartNode(
                GNS3Handler.Instance.projectHandler.GetNodeByName(nodeName)
                );
        }
        // Initialize a Stopwatch instance in order to measure times
        //Stopwatch stopWatch = new Stopwatch();
        // Assign every node with a variable
        VPC     PC1 = (VPC)GNS3Handler.Instance.projectHandler.GetNodeByName(L1Mapping.NodeNamesM1[0]);
        VPC     PC2 = (VPC)GNS3Handler.Instance.projectHandler.GetNodeByName(L1Mapping.NodeNamesM1[1]);
        OpenWRT R1  = (OpenWRT)GNS3Handler.Instance.projectHandler.GetNodeByName(L1Mapping.NodeNamesM1[2]);
        OpenWRT R2  = (OpenWRT)GNS3Handler.Instance.projectHandler.GetNodeByName(L1Mapping.NodeNamesM1[3]);
        OpenWRT R3  = (OpenWRT)GNS3Handler.Instance.projectHandler.GetNodeByName(L1Mapping.NodeNamesM1[4]);
        OpenWRT R4  = (OpenWRT)GNS3Handler.Instance.projectHandler.GetNodeByName(L1Mapping.NodeNamesM1[5]);
        OpenWRT R5  = (OpenWRT)GNS3Handler.Instance.projectHandler.GetNodeByName(L1Mapping.NodeNamesM1[6]);

        OpenWRT[] Routers = new OpenWRT[5] {
            R1, R2, R3, R4, R5
        };

        // We need to wait. Otherwise, nodes won't boot properly. We have set 4:30
        Thread.Sleep(270000);

        // Set up end-point nodes
        L1M1HandlerHelper.SetUpPCs(new VPC[2] {
            PC1, PC2
        }, NetsPrefix);

        /*
         * stopWatch.Start();
         * L1M1HandlerHelper.SetUpPCs(new VPC[2] { PC1, PC2 }, NetsPrefix);
         * using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\aores\Desktop\caso2.txt"))
         * {
         *  file.WriteLine($"Milisegundos en preparar los VPCs: {stopWatch.ElapsedMilliseconds.ToString()}");
         * }
         * stopWatch.Stop();
         */

        // Set-up routers
        L1M1HandlerHelper.SetUpRouters(Routers, NetsPrefix);

        /*
         * stopWatch.Start();
         * L1M1HandlerHelper.SetUpRouters(Routers, NetsPrefix);
         * using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\aores\Desktop\caso2.txt", true))
         * {
         *  file.WriteLine($"Milisegundos en preparar los routers: {stopWatch.ElapsedMilliseconds.ToString()}");
         * }
         * stopWatch.Stop();
         */

        // Set the routing tables signs
        for (int i = 0; i < Routers.Length; i++)
        {
            L1M1HandlerHelper.SetRoutingTables(Routers[i].RoutingTable, NetTables[i]);
        }

        /*
         * stopWatch.Start();
         * for (int i = 0; i < Routers.Length; i++)
         *  L1M1HandlerHelper.SetRoutingTables(Routers[i].RoutingTable, NetTables[i]);
         * using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Users\aores\Desktop\caso2.txt", true))
         * {
         *  file.WriteLine($"Milisegundos en preparar las tablas de encaminamiento del juego: {stopWatch.ElapsedMilliseconds.ToString()}");
         * }
         * stopWatch.Stop();
         */

        // IP of the PC2
        DestinationIP.text = $"Dest:192.168.{NetsPrefix[NetsPrefix.Length - 1]}/24";
        StartCoroutine("Timer");
    }
Esempio n. 6
0
        public async Task <IActionResult> Create([Bind("Name,Type,IPv4CIDR,SubnetSize")] Subnet subnet)
        {
            if (ModelState.IsValid)
            {
                subnet.editable = true;
                switch (Int32.Parse(subnet.SubnetSize))
                {
                case 32766:
                    subnet.IPv4CIDR = subnet.IPv4CIDR + "/17";
                    break;

                case 16382:
                    subnet.IPv4CIDR = subnet.IPv4CIDR + "/18";
                    break;

                case 8190:
                    subnet.IPv4CIDR = subnet.IPv4CIDR + "/19";
                    break;

                case 4094:
                    subnet.IPv4CIDR = subnet.IPv4CIDR + "/20";
                    break;

                case 2046:
                    subnet.IPv4CIDR = subnet.IPv4CIDR + "/21";
                    break;

                case 1022:
                    subnet.IPv4CIDR = subnet.IPv4CIDR + "/22";
                    break;

                case 510:
                    subnet.IPv4CIDR = subnet.IPv4CIDR + "/23";
                    break;

                case 254:
                    subnet.IPv4CIDR = subnet.IPv4CIDR + "/24";
                    break;

                case 126:
                    subnet.IPv4CIDR = subnet.IPv4CIDR + "/25";
                    break;

                case 62:
                    subnet.IPv4CIDR = subnet.IPv4CIDR + "/26";
                    break;

                case 30:
                    subnet.IPv4CIDR = subnet.IPv4CIDR + "/27";
                    break;

                case 14:
                    subnet.IPv4CIDR = subnet.IPv4CIDR + "/28";
                    break;

                case 6:
                    subnet.IPv4CIDR = subnet.IPv4CIDR + "/29";
                    break;

                case 2:
                    subnet.IPv4CIDR = subnet.IPv4CIDR + "/30";
                    break;

                default:
                    ViewData["Exception"] = "Input Invaild!";
                    return(View());
                }
                VPC vpc = await _context.VPCs.FindAsync(1);

                subnet.VPCID = vpc.ID;
                DescribeSubnetsResponse response = await EC2Client.DescribeSubnetsAsync(new DescribeSubnetsRequest
                {
                    Filters = new List <Amazon.EC2.Model.Filter>
                    {
                        new Amazon.EC2.Model.Filter {
                            Name = "vpc-id", Values = new List <string> {
                                vpc.AWSVPCReference
                            }
                        }
                    }
                });

                List <int> ipv6CIDR = new List <int>();
                List <Amazon.EC2.Model.Subnet> subnets = response.Subnets;
                int                  ipv6Subnet        = 0;
                string[]             ipv6CIDRstr       = new string[6];
                DescribeVpcsResponse responseV         = await EC2Client.DescribeVpcsAsync(new DescribeVpcsRequest
                {
                    Filters = new List <Amazon.EC2.Model.Filter>
                    {
                        new Amazon.EC2.Model.Filter {
                            Name = "vpc-id", Values = new List <string> {
                                vpc.AWSVPCReference
                            }
                        }
                    }
                });

                Vpc vpcR = responseV.Vpcs[0];
                VpcIpv6CidrBlockAssociation ipv6CidrBlockAssociation = vpcR.Ipv6CidrBlockAssociationSet[0];
                ipv6CIDRstr = ipv6CidrBlockAssociation.Ipv6CidrBlock.Split(":");
                if (subnets.Count != 0)
                {
                    foreach (Amazon.EC2.Model.Subnet s in subnets)
                    {
                        List <SubnetIpv6CidrBlockAssociation> ipv6 = s.Ipv6CidrBlockAssociationSet;
                        ipv6CIDRstr = ipv6.ElementAt(0).Ipv6CidrBlock.Split(":");
                        ipv6Subnet  = int.Parse(ipv6CIDRstr[3].Substring(2, 2), System.Globalization.NumberStyles.HexNumber);
                        ipv6CIDR.Add(ipv6Subnet);
                    }
                    Boolean flag = false;
                    while (flag != true)
                    {
                        Console.WriteLine("Doing while loop");
                        Console.WriteLine(ipv6Subnet);
                        Boolean passed = false;
                        ++ipv6Subnet;
                        foreach (int i in ipv6CIDR)
                        {
                            if (ipv6Subnet <= ipv6CIDR[i])
                            {
                                passed = false;
                                break;
                            }
                            else
                            {
                                passed = true;
                            }
                        }
                        if (passed == true)
                        {
                            flag = true;
                        }
                    }
                }
                if (ipv6CIDRstr[5].Equals("/56"))
                {
                    if (ipv6Subnet < 9)
                    {
                        subnet.IPv6CIDR = ipv6CIDRstr[0] + ":" + ipv6CIDRstr[1] + ":" + ipv6CIDRstr[2] + ":" + ipv6CIDRstr[3].Substring(0, 2) + "0" + ipv6Subnet.ToString() + "::/64";
                    }
                    else
                    {
                        subnet.IPv6CIDR = ipv6CIDRstr[0] + ":" + ipv6CIDRstr[1] + ":" + ipv6CIDRstr[2] + ":" + ipv6CIDRstr[3].Substring(0, 2) + Convert.ToInt32(ipv6Subnet).ToString() + "::/64";
                    }
                }
                else
                {
                    if (ipv6Subnet < 9)
                    {
                        subnet.IPv6CIDR = ipv6CIDRstr[0] + ":" + ipv6CIDRstr[1] + ":" + ipv6CIDRstr[2] + ":" + ipv6CIDRstr[3].Substring(0, 2) + "0" + ipv6Subnet.ToString() + "::" + ipv6CIDRstr[5];
                    }
                    else
                    {
                        subnet.IPv6CIDR = ipv6CIDRstr[0] + ":" + ipv6CIDRstr[1] + ":" + ipv6CIDRstr[2] + ":" + ipv6CIDRstr[3].Substring(0, 2) + Convert.ToInt32(ipv6Subnet).ToString() + "::" + ipv6CIDRstr[5];
                    }
                }
                CreateSubnetRequest requestS = new CreateSubnetRequest()
                {
                    CidrBlock     = subnet.IPv4CIDR,
                    VpcId         = vpc.AWSVPCReference,
                    Ipv6CidrBlock = subnet.IPv6CIDR
                };
                try
                {
                    CreateSubnetResponse responseS = await EC2Client.CreateSubnetAsync(requestS);

                    if (responseS.HttpStatusCode == HttpStatusCode.OK)
                    {
                        subnet.AWSVPCSubnetReference = responseS.Subnet.SubnetId;
                        await EC2Client.CreateTagsAsync(new CreateTagsRequest
                        {
                            Resources = new List <string>
                            {
                                responseS.Subnet.SubnetId
                            },
                            Tags = new List <Tag>
                            {
                                new Tag("Name", subnet.Name)
                            }
                        });

                        AssociateRouteTableRequest requestRT = new AssociateRouteTableRequest
                        {
                            SubnetId = responseS.Subnet.SubnetId,
                        };
                        if (subnet.Type == Models.SubnetType.Internet)
                        {
                            RouteTable Internet = await _context.RouteTables.FindAsync(2);

                            requestRT.RouteTableId = Internet.AWSVPCRouteTableReference;
                            subnet.RouteTableID    = Internet.ID;
                            await EC2Client.ModifySubnetAttributeAsync(new ModifySubnetAttributeRequest
                            {
                                SubnetId            = responseS.Subnet.SubnetId,
                                MapPublicIpOnLaunch = true
                            });

                            await EC2Client.ModifySubnetAttributeAsync(new ModifySubnetAttributeRequest
                            {
                                SubnetId = responseS.Subnet.SubnetId,
                                AssignIpv6AddressOnCreation = true
                            });
                        }
                        else if (subnet.Type == Models.SubnetType.Extranet)
                        {
                            RouteTable Extranet = await _context.RouteTables.FindAsync(3);

                            requestRT.RouteTableId = Extranet.AWSVPCRouteTableReference;
                            subnet.RouteTableID    = Extranet.ID;
                        }
                        else if (subnet.Type == Models.SubnetType.Intranet)
                        {
                            RouteTable Intranet = await _context.RouteTables.FindAsync(2);

                            requestRT.RouteTableId = Intranet.AWSVPCRouteTableReference;
                            subnet.RouteTableID    = Intranet.ID;
                        }
                        AssociateRouteTableResponse responseRT = await EC2Client.AssociateRouteTableAsync(requestRT);

                        if (responseRT.HttpStatusCode == HttpStatusCode.OK)
                        {
                            subnet.AWSVPCRouteTableAssoicationID = responseRT.AssociationId;
                            _context.Subnets.Add(subnet);
                            await _context.SaveChangesAsync();

                            TempData["Result"] = "Successfully Created!";
                            return(RedirectToAction("Index"));
                        }
                        else
                        {
                            await EC2Client.DeleteSubnetAsync(new DeleteSubnetRequest
                            {
                                SubnetId = subnet.AWSVPCSubnetReference
                            });

                            DescribeVpcsResponse responseD = await EC2Client.DescribeVpcsAsync(new DescribeVpcsRequest
                            {
                                Filters = new List <Amazon.EC2.Model.Filter>
                                {
                                    new Amazon.EC2.Model.Filter {
                                        Name = "vpc-id", Values = new List <string> {
                                            vpc.AWSVPCReference
                                        }
                                    }
                                }
                            });

                            String[] IPBlocks = responseD.Vpcs[0].CidrBlock.Split(".");
                            ViewData["IPCIDR"]    = IPBlocks[0] + "." + IPBlocks[1];
                            ViewData["Exception"] = "Failed to Create!";
                            return(View());
                        }
                    }
                    else
                    {
                        DescribeVpcsResponse responseD = await EC2Client.DescribeVpcsAsync(new DescribeVpcsRequest
                        {
                            Filters = new List <Amazon.EC2.Model.Filter>
                            {
                                new Amazon.EC2.Model.Filter {
                                    Name = "vpc-id", Values = new List <string> {
                                        vpc.AWSVPCReference
                                    }
                                }
                            }
                        });

                        String[] IPBlocks = responseD.Vpcs[0].CidrBlock.Split(".");
                        ViewData["IPCIDR"]    = IPBlocks[0] + "." + IPBlocks[1];
                        ViewData["Exception"] = "Failed to Create!";
                        ViewData["Exception"] = "Failed to Create!";
                        return(View());
                    }
                }
                catch (Amazon.EC2.AmazonEC2Exception e)
                {
                    DescribeVpcsResponse responseD = await EC2Client.DescribeVpcsAsync(new DescribeVpcsRequest
                    {
                        Filters = new List <Amazon.EC2.Model.Filter>
                        {
                            new Amazon.EC2.Model.Filter {
                                Name = "vpc-id", Values = new List <string> {
                                    vpc.AWSVPCReference
                                }
                            }
                        }
                    });

                    String[] IPBlocks = responseD.Vpcs[0].CidrBlock.Split(".");
                    ViewData["IPCIDR"]    = IPBlocks[0] + "." + IPBlocks[1];
                    ViewData["Exception"] = "Failed to Create!";
                    ViewData["Exception"] = e.Message;
                    return(View());
                }
            }
            else
            {
                return(View());
            }
        }
Esempio n. 7
0
        public IActionResult OnePayPayment([Bind("vpc_Customer_Phone,vpc_Customer_Email,vpc_Customer_Id,vpc_Customer_Name")] VPC vpc)
        {
            string value = SessionHelper.GetObjectFromJson <string>(HttpContext.Session, "User");
            var    user  = eMarketContext.TaiKhoan.Include(p => p.ThongTinTaiKhoan).Where(p => p.UserName == value).FirstOrDefault();

            List <GioHang> danhsachhang = SessionHelper.GetObjectFromJson <List <GioHang> >(HttpContext.Session, "cart");
            double         total        = 0;

            foreach (var x in danhsachhang)
            {
                total += x.HangHoa.Gia * x.SoLuong;
            }
            total = VPCRequest.USD_VND * total;
            var current_invoice = CreateInvoice(danhsachhang, vpc.vpc_Customer_Name, vpc.vpc_Customer_Email, vpc.vpc_Customer_Address, vpc.vpc_Customer_Phone);

            HttpContext.Session.SetString("cart", "");

            foreach (var item in danhsachhang)
            {
                var topselling = eMarketContext.TopSelling.Where(p => p.HangHoaId == item.HangHoa.HangHoaId).FirstOrDefault();
                if (topselling == null)
                {
                    var newcolumn = new TopSelling();
                    newcolumn.HangHoaId = item.HangHoa.HangHoaId;
                    newcolumn.SoLan     = 1;
                    eMarketContext.Add(newcolumn);
                    eMarketContext.SaveChanges();
                }
                else
                {
                    topselling.SoLan += 1;
                    eMarketContext.Update(topselling);
                    eMarketContext.SaveChanges();
                }
            }

            //Send request to OnePay
            string     returnURL = Url.Action("OnePayResult", "GioHang", null, Request.Scheme);;
            VPCRequest conn      = new VPCRequest();

            conn.SetSecureSecret(VPCRequest.SECURE_SECRET);
            conn.AddDigitalOrderField("Title", "onepay paygate");
            conn.AddDigitalOrderField("vpc_Locale", "vn");//Chon ngon ngu hien thi tren cong thanh toan (vn/en)
            conn.AddDigitalOrderField("vpc_Version", "2");
            conn.AddDigitalOrderField("vpc_Command", "pay");
            conn.AddDigitalOrderField("vpc_Merchant", VPCRequest.MERCHANT_ID);
            conn.AddDigitalOrderField("vpc_AccessCode", VPCRequest.ACCESS_CODE);
            conn.AddDigitalOrderField("vpc_MerchTxnRef", "HoaDon_" + current_invoice.HoaDonId);
            conn.AddDigitalOrderField("vpc_OrderInfo", "HoaDon_" + current_invoice.HoaDonId);
            conn.AddDigitalOrderField("vpc_Amount", total + "00");
            conn.AddDigitalOrderField("vpc_Currency", "VND");
            conn.AddDigitalOrderField("vpc_ReturnURL", returnURL);

            // Thong tin them ve khach hang. De trong neu khong co thong tin
            conn.AddDigitalOrderField("vpc_Customer_Phone", vpc.vpc_Customer_Phone);
            conn.AddDigitalOrderField("vpc_Customer_Email", vpc.vpc_Customer_Email);
            conn.AddDigitalOrderField("vpc_Customer_Id", "" + user.TaiKhoanId);

            // Dia chi IP cua khach hang
            string ipAddress = _accessor.HttpContext.Connection.RemoteIpAddress.ToString();

            conn.AddDigitalOrderField("vpc_TicketNo", ipAddress);

            // Chuyen huong trinh duyet sang cong thanh toan
            string url = conn.Create3PartyQueryString();

            return(Redirect(url));
        }