Inheritance: ScriptableObject
Example #1
0
 public static void SavePathsInFile(Path path, string fileName)
 {
     string fileSaveName = fileName;  //= @"../../../paths.txt";
     StreamWriter fileOfPathPoints = new StreamWriter(fileSaveName);
     try
     {
         using (fileOfPathPoints)
         {
             foreach (var point in path.PathOfPoints)
             {
                 fileOfPathPoints.WriteLine(point);
             }
         }
     }
     catch (DirectoryNotFoundException dirEx)
     {
         Console.WriteLine("Directory not found! {0}, {1}", dirEx.Message, dirEx.StackTrace);
     }
     catch (IOException ioEx)
     {
         Console.WriteLine(ioEx.Message, ioEx.StackTrace);
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message, ex.StackTrace);
     }
 }
 private static void Main()
 {
     Point3D point = new Point3D(2, 4, 6);
     Point3D pointTwo = new Point3D(8, 5, 3);
     Console.WriteLine("First point:");
     Console.WriteLine(point.ToString());
     Console.WriteLine();
     Console.WriteLine("Second point:");
     Console.WriteLine(pointTwo.ToString());
     Console.WriteLine();
     Console.WriteLine("Distance:");
     Console.WriteLine(DistanceTwo3DPoints.CalcDistance(point, pointTwo));
     Console.WriteLine();
     Console.WriteLine("Center of coordinate system:");
     Console.WriteLine(Point3D.zero.ToString());
     Console.WriteLine();
     Console.WriteLine("Writing in file \"Paths.txt\" first point, second point, first point again!");
     Path firstPath = new Path();
     firstPath.AddPoint(pointTwo);
     firstPath.AddPoint(point);
     firstPath.AddPoint(pointTwo);
     PathStorage.SavePath(firstPath);
     Console.WriteLine("File is saved");
     Console.WriteLine();
     Console.WriteLine("Loading points from file \"Paths.txt\"");
     List<Path> pathList = PathStorage.LoadPath();
     foreach (var path in pathList)
     {
         foreach (var pointers in path.Paths)
         {
             Console.WriteLine(pointers);
         }
     }
 }
Example #3
0
        public static List<Path> LoadPath()
        {
            Path pathToLoad = new Path();
            List<Path> pathsList = new List<Path>();

            using (StreamReader reader = new StreamReader(@"..\..\LoadPaths.txt"))
            {
                string newLine = reader.ReadLine();                

                while (newLine != string.Empty)
                {
                    Point3D newPoint = new Point3D();
                    newLine = reader.ReadLine();
                    
                    newPoint.X = int.Parse(newLine);
                    newLine = reader.ReadLine();
                    newPoint.Y = int.Parse(newLine);
                    newLine = reader.ReadLine();
                    newPoint.Z = int.Parse(newLine);

                    pathToLoad.AddPoint(newPoint);
                    newLine = reader.ReadLine();
                    
                    pathsList.Add(pathToLoad);
                    pathToLoad = new Path();
                    
                    
                }
            }

            return pathsList;
        }
		public void given_different_methods_of_saying_here_in_this_folder()
		{
			an_absolute_path = Environment.CurrentDirectory.ToPath().Combine("chjailing");
			a_relative_path = new Path(".").Combine("chjailing");
			a_relative_path_with_drive = new Path("C:./").Combine("chjailing");
			a_relative_path_with_drive2 = new Path("C:.").Combine("chjailing");
		}
    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    private bool DetectPlayer()
    {
        // Check if the player is within detection range, and if so, attempt
        // detection.
        if (m_playerDistance < MaxDetectionDistance)
        {
            // Calculate the chance of detection based on the range to
            // the player.
            float playerDetectionChance = LinearTransform(m_playerDistance, 0,
                MaxDetectionDistance, MaxDetectionChance, 0);
            if (Random.value < playerDetectionChance)
            {
                if (m_seeker.IsDone())
                {
                    // If we have detected the player, attempt to get a path.
                    Path path = m_seeker.StartPath(transform.position,
                        Player.transform.position);
                    if (!path.error)
                    {
                        // Reset pathfinding variables.
                        m_lastPathfindingUpdate = 0f;
                        m_currentPath = path;
                        m_currentWaypoint = 0;
                        // Change the change to skeleton state and update animation
                        // variables.
                        m_mode = SkeletonMode.Hunting;

                        m_animator.SetFloat("Speed", 1);
                        return true;
                    }
                }
            }
        }
        return false;
    }
Example #6
0
 //    
 //    void OnGUI()
 //    {
 //        Vector3 screen_pos = Camera.main.WorldToScreenPoint (transform.position);
 //        GUI.Label(new Rect(screen_pos.x - 100, Screen.height - screen_pos.y+30, 200, 15), current_hp + "/" + max_hp + " HP", enginePlayerS.hover_text);
 //        GUI.Label(new Rect(screen_pos.x - 100, Screen.height - screen_pos.y + 45, 200, 15), current_ap + "/" + max_ap + " AP", enginePlayerS.hover_text);
 //    }
 public static void moveToHexViaPath(Path _travel_path)
 {
     travel_path = _travel_path.getTraverseOrderList();
     travel_path_en = travel_path.GetEnumerator();
     travel_path_en.MoveNext();
     moving_on_path = true;
 }
                /// <summary>
                /// Generate a path from a set of single-source parent pointers.
                /// </summary>
                /// <param name="from">The start of the path.</param>
                /// <param name="to">The end of the path.</param>
                /// <param name="parents">The set of single-source parent pointers.</param>
                /// <param name="graph">The graph to find the path in.</param>
                /// <returns>The path between <paramref name="from"/> and <paramref name="to"/>, if one exists; <code>null</code> otherwise.</returns>
                public static Path FromParents(uint from, uint to, Dictionary<uint, uint> parents, Graph graph)
                {
                    if (!parents.ContainsKey(to))
                        return null;

                    Path path = new Path();

                    path.Vertices.Add(graph.Vertices[to]);
                    uint current = to, parent;
                    while (parents.TryGetValue(current, out parent))
                    {
                        Vertex v = graph.Vertices[parent];
                        Edge e = v.Neighbours[current];
                        path.Edges.Add(e);
                        path.Vertices.Add(v);
                        path.Weight += e.Weight;
                        path.Capacity = Math.Min(path.Capacity, e.Capacity);
                        current = parent;
                    }

                    path.Edges.Reverse();
                    path.Vertices.Reverse();

                    return path;
                }
 public static List<Path> LoadPath()
 {
     Path loadPath = new Path();
     List<Path> pathsLoaded = new List<Path>();
     using (StreamReader reader = new StreamReader(@"../../PathLoads.txt"))
     {
         string line = reader.ReadLine();
         while (line != null)
         {
             if (line != "-")
             {
                 Point3D point = new Point3D();
                 string[] points = line.Split(',');
                 point.pointX = int.Parse(points[0]);
                 point.pointY = int.Parse(points[1]);
                 point.pointZ = int.Parse(points[2]);
                 loadPath.AddPoint(point);
             }
             else
             {
                 pathsLoaded.Add(loadPath);
                 loadPath = new Path();
             }
             line = reader.ReadLine();
         }
     }
     return pathsLoaded;
 }
Example #9
0
        public static Path LoadPath(string filePath)
        {
            if (String.IsNullOrWhiteSpace(filePath))
            {
                throw new ArgumentException("File name cannot be null or empty.");
            }

            if (!File.Exists(filePath))
            {
                throw new ArgumentException("The specified file doesn't exist in the local file system.");
            }

            Path path = new Path();

            using (StreamReader fileReader = new StreamReader(filePath))
            {
                string line;
                while ((line = fileReader.ReadLine()) != null)
                {
                    string[] coordinates = line.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
                    int x;
                    int y;
                    int z;
                    if (coordinates.Length == 3 &&
                        Int32.TryParse(coordinates[0], out x) &&
                        Int32.TryParse(coordinates[1], out y) &&
                        Int32.TryParse(coordinates[2], out z))
                    {
                        Point3D point = new Point3D(x, y, z);
                        path.AddPoint(point);
                    }
                }
            }
            return path;
        }
Example #10
0
    public static Path LoadPathOfFile(string fileName)
    {
        Path path = new Path();

        using (StreamReader sr = new StreamReader(fileName))
        {
            string input = sr.ReadToEnd();

            string pattern = "{([\\d,.]+), ([\\d,.]+), ([\\d,.]+)}";

            var reg = new Regex(pattern);
            var matchs = reg.Matches(input);

            if (matchs.Count <= 0)
            {
                throw new ApplicationException("Invalid data in file " + fileName);
            }

            foreach (Match match in matchs)
            {
                double x = double.Parse(match.Groups[1].Value);
                double y = double.Parse(match.Groups[2].Value);
                double z = double.Parse(match.Groups[3].Value);

                Point p = new Point(x, y, z);
                path.AddPoint(p);
            }
        }

        return path;
    }
 public static void SavePath(Path path3D, string filePath)
 {
     using (StreamWriter sw = new StreamWriter(filePath, false))
     {
         sw.Write(path3D);
     }
 }
 //In my text files there are more than just one path, because I decided that different paths could be added in txt files with the same names.
 public static void LoadPath(string pathName)
 {
     try
     {
         var reader = new StreamReader(String.Format("{0}.txt", pathName));
         using (reader)
         {
             string buffer = reader.ReadLine();
             do
             {
                 double[] coordinates = buffer
                     .Split(',')
                     .Select(double.Parse)
                     .ToArray();
                 Path currentPath = new Path();
                 for (int i = 0; i < coordinates.Length; i += 3)
                 {
                     Point3D currentPoint = new Point3D(coordinates[i], coordinates[i + 1], coordinates[i + 2]);
                     currentPath.Sequence.Add(currentPoint);
                 }
                 pathes.Add(currentPath);
                 buffer = reader.ReadLine();
             }
             while (buffer != null);
         }
     }
     catch (FileNotFoundException)
     {
         Console.WriteLine("The file could not be found!");
     }
 }
Example #13
0
        public static Path Load(string fileName)
        {
            Path path = new Path();
            string fullFilePath = IO.Path.Combine(@"..\..\Paths", $"{fileName.Trim()}.txt");

            try
            {
                using (IO.StreamReader reader = new IO.StreamReader(fullFilePath))
                {
                    string[] allPoints = reader.ReadToEnd()
                        .Split(new string[] { "\n", "\r" }, StringSplitOptions.RemoveEmptyEntries);

                    foreach (var point in allPoints)
                    {
                        double[] coordinates = point.Trim('[', ']', ' ')
                            .Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries)
                            .Select(double.Parse)
                            .ToArray();

                        path.AddPoint(new Point3D(coordinates[0], coordinates[1], coordinates[2]));
                    }
                }
            }
            catch (IO.FileNotFoundException)
            {
                Console.WriteLine($"The file path {fileName} cannot be found");
            }

            return path;
        }
Example #14
0
	/** Called when a path has completed it's calculation */
	public void OnPathComplete (Path p) {
		
		/*if (Time.time-lastPathSearch >= repathRate) {
			Repath ();
		} else {*/
			StartCoroutine (WaitToRepath ());
		//}
		
		//If the path didn't succeed, don't proceed
		if (p.error) {
			return;
		}
		
		//Get the calculated path as a Vector3 array
		path = p.vectorPath.ToArray();
		
		//Find the segment in the path which is closest to the AI
		//If a closer segment hasn't been found in '6' iterations, break because it is unlikely to find any closer ones then
		float minDist = Mathf.Infinity;
		int notCloserHits = 0;
		
		for (int i=0;i<path.Length-1;i++) {
			float dist = AstarMath.DistancePointSegmentStrict (path[i],path[i+1],tr.position);
			if (dist < minDist) {
				notCloserHits = 0;
				minDist = dist;
				pathIndex = i+1;
			} else if (notCloserHits > 6) {
				break;
			}
		}
	}
Example #15
0
 public PathReadyEventPayload(
     GameObject gameObject,
     Path path)
 {
     this.gameObject = gameObject;
     this.path = path;
 }
 public ProtoUnzipArchiveTask(Path path, string archiveFilename, bool isLocal = false)
 {
     Guard.AgainstEmpty(archiveFilename);
     _path = path;
     _archiveFilename = ReplaceTokens(archiveFilename);
     _isLocal = isLocal;
 }
        /// <summary>
        /// Reads a path of 3D points from the Location/fileName that cane be set through the properties PathName and FileName
        /// </summary>
        /// <returns>Collection of Point3D</returns>
        static public Path ReadPathFromFile()
        {
            Path resultPath = new Path();
            StreamReader reader = new StreamReader(Location + FileName);
            string fileContents;
            string[] splitters = { "--", "\n", "[", "]", ",", ":","Point","->","\r\n"," "};

            //reads the contents of file 
            using (reader)
            {
                fileContents = reader.ReadToEnd();
            }
            //points is an array of strings containing ine [0] - the Path name and in all next 4-s - Point3d 
            string[] points = fileContents.Split(splitters, StringSplitOptions.RemoveEmptyEntries);

            //first is the name of the whole path
            resultPath.Name = points[0];

            //for every 4 elements in the points array get the nex Point X,Y,Z and Name and put them in a new instance of point
            for (int i = 1; i < points.Length; i += 4)
            {
                Point3D nextPoint = new Point3D(int.Parse(points[i + 1]), int.Parse(points[i + 2]), int.Parse(points[i + 3]), points[i]);
                resultPath.PathAddPoint = nextPoint;
            }

            return resultPath;
        }
        public static List<Path> LoadPath()
        {
            Path path = new Path();
            List<Path> pathList = new List<Path>();

            using (StreamReader reader = new StreamReader(@"../../LoadPath.txt"))
            {
                string line = reader.ReadLine();

                while (line != null)
                {
                    if (line != "END OF PATH")
                    {
                        Point3D point = new Point3D();
                        string[] coordinates = line.Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries);
                        point.X = int.Parse(coordinates[0]);
                        point.Y = int.Parse(coordinates[1]);
                        point.Z = int.Parse(coordinates[2]);
                        path.AddPoint(point);
                    }
                    else
                    {
                        pathList.Add(path);
                        path = new Path();
                    }
                    line = reader.ReadLine();
                }
            }
            return pathList;
        }
Example #19
0
        public static void SavePathToFile(Path path, string fileName)
        {
            try
            {
                StreamWriter writer = new StreamWriter(fileName);

                using (writer)
                {
                    for (int i = 0; i < path.Count; i++)
                    {
                        writer.WriteLine(path.PointPath[i]);
                    }
                }
            }
            catch (FileNotFoundException)
            {
                Console.Error.WriteLine("Can not find file {0}.", fileName);
            }
            catch (DirectoryNotFoundException)
            {
                Console.Error.WriteLine("Invalid directory in file path.");
            }
            catch (IOException)
            {
                Console.Error.WriteLine("Can not open file {0}.", fileName);
            }
        }
Example #20
0
        /// <summary>
        /// Extracts some or all of the files from the specified MSI and returns a <see cref="FileEntryGraph"/> representing the files that were extracted.
        /// </summary>
        /// <param name="msiFileName">The msi file to extract or null to extract all files.</param>
        /// <param name="fileNamesToExtractOrNull">The files to extract from the MSI or null to extract all files.</param>
        /// <param name="outputDir">A relative directory to extract output to or an empty string to use the default output directory.</param>
        /// <param name="skipReturningFileEntryGraph">True to return the <see cref="FileEntryGraph"/>. Otherwise null will be returned.</param>
        protected FileEntryGraph ExtractFilesFromMsi(string msiFileName, string[] fileNamesToExtractOrNull, Path outputDir, bool returnFileEntryGraph)
        {
            outputDir = GetTestOutputDir(outputDir, msiFileName);

            if (FileSystem.Exists(outputDir))
            {
                FileSystem.RemoveDirectory(outputDir, true);
            }
            Debug.Assert(!FileSystem.Exists(outputDir), "Directory still exists!");
            FileSystem.CreateDirectory(outputDir);

            //ExtractViaCommandLine(outputDir, msiFileName);
            ExtractInProcess(msiFileName, outputDir.PathString, fileNamesToExtractOrNull);
            if (returnFileEntryGraph)
            {
                //  build actual file entries extracted
                var actualEntries = FileEntryGraph.GetActualEntries(outputDir.PathString, msiFileName);
                // dump to actual dir (for debugging and updating tests)
                actualEntries.Save(GetActualOutputFile(msiFileName));
                return actualEntries;
            }
            else
            {
                return null;
            }
        }
Example #21
0
 internal PathInfo(PSDriveInfo drive, ProviderInfo provider, Path path, SessionState sessionState)
 {
     Drive = drive;
     Provider = provider;
     _path = path;
     _sessionState = sessionState;
 }
 internal static Path LoadPath()
 {
     Path loadPath = new Path();
     try
     {
         using (StreamReader reader = new StreamReader(@"../../savedPaths.txt"))
         {
             while (reader.Peek() >= 0)
             {
                 String line = reader.ReadLine();
                 String[] splittedLine = line.Split(new char[] { '(', ',', ')' }, StringSplitOptions.RemoveEmptyEntries);
                 loadPath.AddPoint(new Point3D(int.Parse(splittedLine[0]), int.Parse(splittedLine[1]), int.Parse(splittedLine[2])));
             }
         }
     }
     catch (FileNotFoundException)
     {
         Console.WriteLine("File not found, try adding a new file");
     }
     catch (IOException io)
     {
         Console.WriteLine(io.Message);
     }
     catch (OutOfMemoryException ome)
     {
         Console.WriteLine(ome.Message);
     }
     finally { }
     return loadPath;
 }
Example #23
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ManualPath"/> class.
        /// </summary>
        /// <param name="replanCallback">The replan callback.</param>
        /// <param name="path">The path.</param>
        public ManualPath(Replan replanCallback, Path path)
        {
            Ensure.ArgumentNotNull(path, "path");

            this.onReplan = replanCallback;
            this.path = path;
        }
		public IDirectory LinkTo(Path path)
		{
			Contract.Requires(path != null);
			Contract.Ensures(Contract.Result<IDirectory>() != null);

			throw new NotImplementedException();
		}
Example #25
0
 private void OnPath(Path p)
 {
     if (p.Success)
     {
         path = p;
     }
 }
Example #26
0
        private void GetPath(Path obj)
        {
            Connects = new ObservableCollection<Connector>();

            Points = new ObservableCollection<Point>(
                obj.Points.Select(x => new Point()
                    {
                        X = ((x.From.X < 0) ? Math.Abs(Math.Abs(x.From.X) - 4096) : Math.Abs(x.From.X) + 4096),
                        Y = ((x.From.Z > 0) ? Math.Abs(Math.Abs(x.From.Z) - 5632) : Math.Abs(x.From.Z) + 5632)
                    })
            );

            for(int i = 0; i < Points.Count - 1; i++)
                Connects.Add(new Connector()
                {
                    StartPoint = Points[i],
                    EndPoint = Points[i+1]
                });

            Connects.Add(new Connector()
            {
                StartPoint = Points[Points.Count - 1],
                EndPoint = Points[0]
            });

            Collection = new CompositeCollection()
            {
                new CollectionContainer() { Collection = Points },
                new CollectionContainer() { Collection = Connects }
            };
        }
Example #27
0
 public void OnPathComplete( Path p )
 {
     if ( !p.error ) {
         path = p;
         currentWayPoint = 0;
     }
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="ProgressiveVectorField"/> class.
        /// </summary>
        /// <param name="group">The group.</param>
        /// <param name="path">The path.</param>
        /// <param name="options">The options.</param>
        public ProgressiveVectorField(TransientGroup<IUnitFacade> group, Path path, VectorFieldOptions options)
        {
            Ensure.ArgumentNotNull(group, "group");
            this.group = group;

            _currentPath = path;

            var modelUnit = group.modelUnit;
            _unitProperties = modelUnit;
            var pathOptions = modelUnit.pathFinderOptions;

            // cache options locally
            _allowCornerCutting = pathOptions.allowCornerCutting;
            _allowDiagonals = !pathOptions.preventDiagonalMoves;
            _announceAllNodes = modelUnit.pathNavigationOptions.announceAllNodes;

            _obstacleStrengthFactor = options.obstacleStrengthFactor;
            _builtInContainment = options.builtInContainment;
            _updateInterval = options.updateInterval;
            _paddingIncrease = options.paddingIncrease;
            _maxExtraPadding = options.maxExtraPadding;
            _boundsPadding = options.boundsPadding;
            _boundsRecalculateThreshold = options.boundsRecalculateThreshold;
            _expectedGroupGrowthFactor = 1f + options.expectedGroupGrowthFactor;

            // pre-allocate lists memory
            _openSet = new SimpleQueue<Cell>(31);
            _tempWalkableNeighbours = new DynamicArray<Cell>(8);
            _extraTempWalkableNeighbours = new DynamicArray<Cell>(8);
            _groupBounds = new RectangleXZ(group.centerOfGravity, _boundsPadding, _boundsPadding);
        }
Example #29
0
        public static Path Load(string pathName)
        {
            Path path = new Path();
            string fullPath = GenerateFullPath(pathName);

            try
            {
                using (var reader = new StreamReader(fullPath))
                {
                    string[] points = reader.ReadToEnd()
                        .Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);

                    foreach (var point in points)
                    {
                        double[] coordinates = point.Trim('[').Trim(']')
                            .Split(new[] { ' ', ';', 'X', 'Y', 'Z', ':' }, StringSplitOptions.RemoveEmptyEntries)
                            .Select(x => double.Parse(x))
                            .ToArray();

                        path.AddPoint(new Point3D(coordinates[0], coordinates[1], coordinates[2]));
                    }
                }
            }
            catch (FileNotFoundException)
            {
                Console.WriteLine("The path \"{0}\" couldn't be found", pathName);
                return null;
            }

            return path;
        }
Example #30
0
        public static List<Path> LoadPathsFromFile()
        {
            var paths = new List<Path>();
            var pathReader = new StreamReader(LoadFilePath);
            using (pathReader)
            {
                int numberOfPaths = int.Parse(pathReader.ReadLine());
                for (int i = 0; i < numberOfPaths; i++)
                {
                    int numberOfPointsinPath = int.Parse(pathReader.ReadLine());
                    var path = new Path();
                    string[] currentLine;
                    for (int k = 0; k < numberOfPointsinPath; k++)
                    {
                        currentLine = pathReader.ReadLine().Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries);
                        double x = double.Parse(currentLine[0]);
                        double y = double.Parse(currentLine[1]);
                        double z = double.Parse(currentLine[2]);
                        path.AddPoint(new Point3D(x, y, z));
                    }

                    paths.Add(path);
                }
            }

            return paths;
        }
Example #31
0
        public async Task SaveToBackupFolder(string fileName, byte[] content)
        {
            var fullPath = Path.Combine(backupRootPath, fileName);

            File.WriteAllBytes(fullPath, content);
        }
Example #32
0
		public void SendEmail(EmailAddress recipient, string subject, string textBody, string htmlBody, List<string> attachments)
		{
			ValidationException ex = new ValidationException();

			if (recipient == null)
				ex.AddError("recipientEmail", "Recipient is not specified.");
			else
			{
				if (string.IsNullOrEmpty(recipient.Address))
					ex.AddError("recipientEmail", "Recipient email is not specified.");
				else if (!recipient.Address.IsEmail())
					ex.AddError("recipientEmail", "Recipient email is not valid email address.");
			}

			if (string.IsNullOrEmpty(subject))
				ex.AddError("subject", "Subject is required.");

			ex.CheckAndThrow();

			var message = new MimeMessage();
			if (!string.IsNullOrWhiteSpace(DefaultSenderName))
				message.From.Add(new MailboxAddress(DefaultSenderName, DefaultSenderEmail));
			else
				message.From.Add(new MailboxAddress(DefaultSenderEmail));

			if (!string.IsNullOrWhiteSpace(recipient.Name))
				message.To.Add(new MailboxAddress(recipient.Name, recipient.Address));
			else
				message.To.Add(new MailboxAddress(recipient.Address));

			if (!string.IsNullOrWhiteSpace(DefaultReplyToEmail))
				message.ReplyTo.Add(new MailboxAddress(DefaultReplyToEmail));

			message.Subject = subject;

			var bodyBuilder = new BodyBuilder();
			bodyBuilder.HtmlBody = htmlBody;
			bodyBuilder.TextBody = textBody;

			if (attachments != null && attachments.Count > 0)
			{
				foreach (var att in attachments)
				{
					var filepath = att;

					if (!filepath.StartsWith("/"))
						filepath = "/" + filepath;

					filepath = filepath.ToLowerInvariant();

					if (filepath.StartsWith("/fs"))
						filepath = filepath.Substring(3);

					DbFileRepository fsRepository = new DbFileRepository();
					var file = fsRepository.Find(filepath);
					var bytes = file.GetBytes();

					var extension = Path.GetExtension(filepath).ToLowerInvariant();
					new FileExtensionContentTypeProvider().Mappings.TryGetValue(extension, out string mimeType);

					var attachment = new MimePart(mimeType)
					{
						Content = new MimeContent(new MemoryStream(bytes)),
						ContentDisposition = new ContentDisposition(ContentDisposition.Attachment),
						ContentTransferEncoding = ContentEncoding.Base64,
						FileName = Path.GetFileName(filepath)
					};

					bodyBuilder.Attachments.Add(attachment);
				}
			}

			SmtpInternalService.ProcessHtmlContent(bodyBuilder);
			message.Body = bodyBuilder.ToMessageBody();

			using (var client = new SmtpClient())
			{
				//accept all SSL certificates (in case the server supports STARTTLS)
				client.ServerCertificateValidationCallback = (s, c, h, e) => true;

				client.Connect(Server, Port, ConnectionSecurity);

				if (!string.IsNullOrWhiteSpace(Username))
					client.Authenticate(Username, Password);

				client.Send(message);
				client.Disconnect(true);
			}

			Email email = new Email();
			email.Id = Guid.NewGuid();
			email.Sender = new EmailAddress { Address = DefaultSenderEmail, Name = DefaultSenderName };
			email.ReplyToEmail = DefaultReplyToEmail;
			email.Recipients = new List<EmailAddress> { recipient };
			email.Subject = subject;
			email.ContentHtml = htmlBody;
			email.ContentText = textBody;
			email.CreatedOn = DateTime.UtcNow;
			email.SentOn = email.CreatedOn;
			email.Priority = EmailPriority.Normal;
			email.Status = EmailStatus.Sent;
			email.ServerError = string.Empty;
			email.ScheduledOn = null;
			email.RetriesCount = 0;
			email.ServiceId = Id;
			if (attachments != null && attachments.Count > 0)
			{
				DbFileRepository fsRepository = new DbFileRepository();
				foreach (var att in attachments)
				{
					var filepath = att;

					if (!filepath.StartsWith("/"))
						filepath = "/" + filepath;

					filepath = filepath.ToLowerInvariant();

					if (filepath.StartsWith("/fs"))
						filepath = filepath.Substring(3);

					var file = fsRepository.Find(filepath);
					if (file == null)
						throw new Exception($"Attachment file '{filepath}' not found.");

					email.Attachments.Add(filepath);
				}
			}
			new SmtpInternalService().SaveEmail(email);
		}
        public static string function_61602(string param_61602)
        {
            string tainted_2 = null;
            string tainted_3 = null;

            tainted_2 = param_61602;

            string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars()) + ";";
            Regex  r           = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));

            tainted_3 = r.Replace(tainted_2, "");

            return(tainted_3);
        }
Example #34
0
		public void Setup()
		{
			var dir = TestContext.CurrentContext.TestDirectory;
			var testName = TestContext.CurrentContext.Test.Name;
			_installationPath = Path.Combine(dir, testName);
		}
Example #35
0
		private static void PrintLogFile()
		{
			var fname = Path.Combine(Constants.AppDataLocalFolder, "Tailviewer.log");
			Console.WriteLine(File.ReadAllText(fname));
		}
 protected virtual PackageReferenceFile GetPackageReferenceFile(string path)
 {
     return new PackageReferenceFile(Path.GetFullPath(path));
 }
 protected internal virtual IFileSystem CreateFileSystem(string path)
 {
     path = Path.GetFullPath(path);
     return new PhysicalFileSystem(path);
 }
Example #38
0
        public ActionResult SWIGetFolderDetail(string path)
        {
            WriteDebug("SWIGetFolderDetail");
            try
            {
                SWIFolder folder = getFolder(path);
                var       files  = new List <SWIFile>();
                if (folder.right > 0)
                {
                    foreach (string newPath in Directory.GetFiles(folder.GetFullPath(), "*.*"))
                    {
                        //check right on files only
                        if (folder.files && FileHelper.IsSealReportFile(newPath))
                        {
                            continue;
                        }
                        if (folder.IsPersonal && newPath.ToLower() == WebUser.ProfilePath.ToLower())
                        {
                            continue;
                        }

                        files.Add(new SWIFile()
                        {
                            path     = folder.Combine(Path.GetFileName(newPath)),
                            name     = Repository.TranslateFileName(newPath) + (FileHelper.IsSealReportFile(newPath) ? "" : Path.GetExtension(newPath)),
                            last     = System.IO.File.GetLastWriteTime(newPath).ToString("G", Repository.CultureInfo),
                            isReport = FileHelper.IsSealReportFile(newPath),
                            right    = folder.right
                        });
                    }
                }
                SetCookie(SealLastFolderCookieName, path);

                return(Json(new SWIFolderDetail()
                {
                    folder = folder, files = files.ToArray()
                }));
            }
            catch (Exception ex)
            {
                return(HandleSWIException(ex));
            }
        }
Example #39
0
        public static async Task RunOptimization(TestcaseBlockerDataset dataset)
        {
            if (dataset is null)
            {
                Console.WriteLine("Cannot run optimization for an empty dataset. First generate or load a dataset.");
                return;
            }

            var debugOutput = true;

            Console.Write("Suppress output information for each generation (y)? ");
            if (Console.ReadLine().ToLower() == "y")
            {
                debugOutput = false;
            }

            var watch = new Stopwatch();

            watch.Start();

            var optimizer = new Optimizer(dataset);

            if (debugOutput)
            {
                optimizer.ChromosomeEvaluated += Optimizer_ChromosomeEvaluated;
                optimizer.GenerationEvaluated += Optimizer_GenerationEvaluated;
            }
            else
            {
                optimizer.GenerationEvaluated += Optimizer_GenerationProgress;
            }
            var result = optimizer.Optimize();

            var duration = TimeSpan.FromMilliseconds(watch.ElapsedMilliseconds);

            watch.Stop();

            var resolvedBlockers = string.Join(",", result.ResolvedBlockers.Select(x => x.Name).ToList());

            if (resolvedBlockers.Length > 100)
            {
                resolvedBlockers = resolvedBlockers.Substring(0, 97) + "...";
            }

            var resolvedTestcases = string.Join(",", result.ResolvedTestcases.Select(x => x.Id).ToList());

            if (resolvedTestcases.Length > 100)
            {
                resolvedTestcases = resolvedTestcases.Substring(0, 97) + "...";
            }

            var resolvedTestcasesIncludingUnblocked = string.Join(",", result.ResolvedTestcasesIncludingUnblocked.Select(x => x.Id).ToList());

            if (resolvedTestcasesIncludingUnblocked.Length > 100)
            {
                resolvedTestcasesIncludingUnblocked = resolvedTestcasesIncludingUnblocked.Substring(0, 97) + "...";
            }

            Console.WriteLine();
            Console.WriteLine($"Duration                      : {duration.ToString()} (including output)");
            Console.WriteLine($"Best solution fitness         : {result.Fitness}");
            Console.WriteLine($"Resolved Blockers             : ({result.NumberOfResolvedBlockers}/{result.Cost}) [{resolvedBlockers}]");
            Console.WriteLine($"Resolved Testcases            : ({result.NumberOfResolvedTestcases}/{result.Value}) [{resolvedTestcases}]");
            Console.WriteLine($"Resolved Testcases w/unblocked: ({result.NumberOfResolvedTestcasesIncludingUnblocked}/{result.ValueIncludingUnblocked}) [{resolvedTestcasesIncludingUnblocked}]");
            Console.WriteLine();
            Console.Write("Save result (y|n)? ");

            var saveResult = Console.ReadLine().Trim().ToLower();

            if (saveResult == "y")
            {
                Console.Write("Enter filename without extension: ");
                string filename = Console.ReadLine();

                var path = Path.Combine(GetDataPath(), filename + ".json");

                Console.WriteLine($"Saving result to {path}");

                await IOOperations.SaveAsync <OptimizationResult>(path, result);
            }
        }
Example #40
0
        public ActionResult SWIMoveFile(string source, string destination, bool copy)
        {
            WriteDebug("SWIMoveFile");
            try
            {
                SWIFolder folderSource = getParentFolder(source);
                if (folderSource.right == 0)
                {
                    throw new Exception("Error: no right on this folder");
                }
                SWIFolder folderDest = getParentFolder(destination);
                if ((FolderRight)folderDest.right != FolderRight.Edit)
                {
                    throw new Exception("Error: no right to edit on the destination folder");
                }

                string sourcePath      = getFullPath(source);
                string destinationPath = getFullPath(destination);
                if (!System.IO.File.Exists(sourcePath))
                {
                    throw new Exception("Error: source path is incorrect");
                }
                if (folderDest.files && FileHelper.IsSealReportFile(sourcePath))
                {
                    throw new Exception(Translate("Warning: only files (and not reports) can be copied to this folder."));
                }
                if (System.IO.File.Exists(destinationPath) && copy)
                {
                    destinationPath = FileHelper.GetUniqueFileName(Path.GetDirectoryName(destinationPath), Path.GetFileNameWithoutExtension(destinationPath) + " - Copy" + Path.GetExtension(destinationPath), Path.GetExtension(destinationPath));
                }

                bool hasSchedule = (FileHelper.IsSealReportFile(sourcePath) && FileHelper.ReportHasSchedule(sourcePath));
                FileHelper.MoveSealFile(sourcePath, destinationPath, copy);
                if (hasSchedule)
                {
                    //Re-init schedules...
                    var report = Report.LoadFromFile(destinationPath, Repository);
                    if (copy)
                    {
                        //remove schedules
                        report.Schedules.Clear();
                        report.SaveToFile();
                    }
                    report.SchedulesWithCurrentUser = false;
                    report.SynchronizeTasks();
                }
                return(Json(new object { }));
            }
            catch (Exception ex)
            {
                return(HandleSWIException(ex));
            }
        }
Example #41
0
		private void MainForm_Load(object sender, EventArgs e)
		{
			LogLine("Umbrella2 NEARBY Interface");
			LogLine("Core", "Loading configuration");

			try
			{
				var ConfSet = Configurator.ReadConfigFile(ConfigFile);
				Config = Configurator.ReadConfig(ConfSet);
			}
			catch (Exception ex)
			{
				LogLine("Core", "Failed to load configuration file. Error follows:\n" + ex.ToString());
				Config = new FrontendConfig { LoadLast = false, RootInputDir = string.Empty, RootOutputDir = Path.GetTempPath(), WatchDir = false };
				LogLine("Core", "Using default configuration");
			}

			LogLine("Core", "Loaded configuration file");

			bool LoadedLast = false;
			if (Config.LoadLast)
			{
				if (TryLoadLast()) { LogLine("Core", "Found field not yet run"); LoadedLast = true; }
				else LogLine("Core", "All fields ran");
			}
			try
			{
				if (Config.WatchDir & !LoadedLast) { fileSystemWatcher1.Path = Config.RootInputDir; fileSystemWatcher1.EnableRaisingEvents = true; LogLine("Core", "Watching directory for changes"); }
			}
			catch { LogLine("Core", "Could not watch root input directory."); }
			Pipeline = new Umbrella2.Pipeline.Standard.ClassicPipeline();
			textBox3.Text = Config.RootOutputDir;
			LogLine("Core", "Loading integrated plugins");
			foreach (System.Reflection.Assembly asm in Program.GetAssemblies())
				Plugins.LoadableTypes.RegisterNewTypes(asm.GetTypes());
			LogLine("Core", "Plugins loaded");
			LogLine("Core", "Initialized");

			if (Program.Args.Length != 0)
			{
				LogLine("Automation", "Arguments specified on the command line.");
				if (Program.Args[0] == "autofield")
				{
					LogLine("Automation", "Automatically running field " + Program.Args[1]);
					textBox1.Text = Program.Args[1];
					textBox1_Validating(null, null);
					textBox2_Validating(null, null);
					button1_Click(null, null);
				}
			}
		}
 public DataBaseService()
 {
     connection = new SQLiteConnection($"Data Source={Path.GetFullPath(@"..\..\")}AmicsDeLaMusica.db;New=False;");
 }
Example #43
0
    public static string GetCachedFileNameFromUrl(string url)
    {
      var fn = url.Replace("https://", "").Replace("/", "-").Replace(":", "-").Replace("http", "").Replace("?", "!").Replace("|", "!").Replace("---", "");
      var folder = Path.Combine(OneDrive.WebCacheFolder, fn.Split('-')[0]);
#if CS8
      fn = fn[(fn.IndexOf("-") + 1)..]; // == fn = fn.Substring(fn.IndexOf("-") + 1);
Example #44
0
        // Entrypoint
        static void Main(string[] args)
        {
            Console.WriteLine("HACbuild - {0}", Assembly.GetExecutingAssembly().GetName().Version);

            if (LoadKeys())
            {
                Console.WriteLine("XCI Header Key loaded successfully:\n{0}", BitConverter.ToString(XCIManager.XCI_GAMECARDINFO_KEY));

                byte[] keyHash = Program.SHA256.ComputeHash(XCIManager.XCI_GAMECARDINFO_KEY);

                if (Enumerable.SequenceEqual <byte>(keyHash, XCIManager.XCI_GAMECARD_KEY_SHA256))
                {
                    Console.WriteLine("XCI Header Key is correct!");
                }
                else
                {
                    Console.WriteLine("[WARN] Invalid XCI Header Key");
                }
            }
            else
            {
                Console.WriteLine("[WARN] Could not load XCI Header Key");
            }

            // Configure AES
            AES128CBC.BlockSize = 128;
            AES128CBC.Mode      = CipherMode.CBC;
            AES128CBC.Padding   = PaddingMode.Zeros;

            if (args.Length < 3)
            {
                PrintUsage();
                return;
            }

            // TODO Decent command line argument parsing (this is... ugly).
            switch (args[0])
            {
            case "read":
                switch (args[1])
                {
                case "xci":
                    Console.WriteLine("Reading {0}", args[2]);
                    XCIManager.xci_header    header = XCIManager.GetXCIHeader(args[2]);
                    XCIManager.gamecard_info gcInfo = XCIManager.DecryptGamecardInfo(header);


                    Console.WriteLine(header.ToString());
                    Console.WriteLine(gcInfo.ToString());

                    // TODO Move somewhere else - dump to ini
                    string folder  = Path.GetDirectoryName(Path.GetFullPath(args[2]));        // Is GetFullPath needed?
                    string iniPath = Path.Combine(folder, Path.GetFileNameWithoutExtension(args[2])) + ".ini";

                    IniFile ini = new IniFile(iniPath);

                    ini.Write("PackageID", header.PackageID.ToString(), "XCI_Header");
                    ini.WriteBytes("GamecardIV", header.GamecardIV, "XCI_Header");
                    ini.Write("KEKIndex", header.KEK.ToString(), "XCI_Header");
                    ini.WriteBytes("InitialDataHash", header.InitialDataHash, "XCI_Header");

                    ini.Write("Version", gcInfo.Version.ToString(), "GameCard_Info");
                    ini.Write("AccessControlFlags", gcInfo.AccessControlFlags.ToString(), "GameCard_Info");
                    ini.Write("ReadWaitTime", gcInfo.ReadWaitTime.ToString(), "GameCard_Info");
                    ini.Write("ReadWaitTime2", gcInfo.ReadWaitTime2.ToString(), "GameCard_Info");
                    ini.Write("WriteWriteTime", gcInfo.WriteWriteTime.ToString(), "GameCard_Info");
                    ini.Write("WriteWriteTime2", gcInfo.WriteWriteTime2.ToString(), "GameCard_Info");
                    ini.Write("FirmwareMode", gcInfo.FirmwareMode.ToString(), "GameCard_Info");
                    ini.Write("CUPVersion", gcInfo.CUPVersion.ToString(), "GameCard_Info");
                    ini.Write("CUPID", gcInfo.CUPID.ToString(), "GameCard_Info");
                    // end dump to ini



                    break;

                default:
                    Console.WriteLine("Usage: hacbuild.exe read xci <IN>");
                    break;
                }
                break;

            case "hfs0":
                HFS0Manager.BuildHFS0(args[1], args[2]);
                break;

            case "xci":
                XCIManager.BuildXCI(args[1], args[2]);
                break;

            case "xci_auto":
                string inPath  = Path.Combine(Environment.CurrentDirectory, args[1]);
                string outPath = Path.Combine(Environment.CurrentDirectory, args[2]);
                string tmpPath = Path.Combine(inPath, "root_tmp");
                Directory.CreateDirectory(tmpPath);

                HFS0Manager.BuildHFS0(Path.Combine(inPath, "secure"), Path.Combine(tmpPath, "secure"));
                HFS0Manager.BuildHFS0(Path.Combine(inPath, "normal"), Path.Combine(tmpPath, "normal"));
                HFS0Manager.BuildHFS0(Path.Combine(inPath, "update"), Path.Combine(tmpPath, "update"));
                if (Directory.Exists(Path.Combine(inPath, "logo")))
                {
                    HFS0Manager.BuildHFS0(Path.Combine(inPath, "logo"), Path.Combine(tmpPath, "logo"));
                }
                HFS0Manager.BuildHFS0(tmpPath, Path.Combine(inPath, "root.hfs0"));

                XCIManager.BuildXCI(inPath, outPath);

                File.Delete(Path.Combine(inPath, "root.hfs0"));
                Directory.Delete(tmpPath, true);
                break;

            default:
                PrintUsage();
                break;
            }
        }
Example #45
0
        public static void Main(string[] args)
        {
            string tainted_2 = null;
            string tainted_3 = null;


            tainted_2 = Console.ReadLine();

            tainted_3 = tainted_2;

            if ((Math.Sqrt(42) <= 42))
            {
                {}
            }
            else if (!(Math.Sqrt(42) <= 42))
            {
                string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
                Regex  r           = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));
                tainted_3 = r.Replace(tainted_2, "");
            }
            else
            {
                {}
            }

            //flaw

            File.Exists(tainted_3);
        }
Example #46
0
		static bool IsFitsExtension(string File)
		{
			string Extension = Path.GetExtension(File);
			if (Extension == ".fit" || Extension == ".fits" || Extension == ".fts") return true;
			return false;
		}
Example #47
0
        public static async Task <bool> GoToNextSite(AdvertiseType type, short mode)
        {
            try
            {
                //mode 0 => حرکت رو به جلو
                //mode 1 => از سر گیری سایت ها بعد از ریستارت مورم
                //SettingBusiness _cls;
                //var res = await SettingBusiness.GetAllAsync();
                //_cls = res.Count == 0 ? new SettingBusiness() : res[0];
                var path = Path.Combine(Application.StartupPath, "SiteRate.txt");
                var lst  = File.ReadAllLines(path).ToList();
                if (!lst.Any())
                {
                    return(false);
                }
                var index = "";
                if (mode == 0)
                {
                    for (var i = 0; i < lst.Count; i++)
                    {
                        if (lst[i] != type.ToString())
                        {
                            continue;
                        }
                        if (i + 1 == lst.Count)
                        {
                            index = null;
                            break;
                        }

                        index = lst[i + 1];
                        break;
                    }
                }
                else
                {
                    CloseAllChromeWindows();
                    index = lst[0];
                }

                switch (index)
                {
                case "Divar":
                    //if (_cls.DivarSetting.CountAdvInIp != 0)
                    //{
                    //    var divar = await DivarAdv.GetInstance();
                    //    await divar.StartRegisterAdv();
                    //    return true;
                    //}
                    break;

                case "Sheypoor":
                    //if (_cls.SheypoorSetting.CountAdvInIp != 0)
                    //{
                    //    var sheypoor = await SheypoorAdv.GetInstance();
                    //    await sheypoor.StartRegisterAdv();
                    //    return true;
                    //}
                    break;
                }

                return(false);
            }
            catch (Exception ex)
            {
                WebErrorLog.ErrorInstence.StartErrorLog(ex);
                return(false);
            }
        }
Example #48
0
 public BookmarkFolderNode(string fileName)
 {
     drawDefault   = false;
     this.fileName = fileName;
     fileNameText  = Path.GetFileName(fileName) + StringParser.Parse(" ${res:MainWindow.Windows.SearchResultPanel.In} ") + Path.GetDirectoryName(fileName);
     icon          = IconService.GetBitmap(IconService.GetImageForFile(fileName));
     Nodes.Add(new TreeNode());
 }
Example #49
0
 public void HandleAreaCode()
 {
     try
     {
         string str5;
         RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\fwkp.exe", true);
         string[] subKeyNames = key.GetSubKeyNames();
         if ((subKeyNames == null) || (subKeyNames.Length < 1))
         {
             goto Label_034E;
         }
         string path = "";
         string dbpath = "";
         string str3 = key.GetValue("Path", "") as string;
         str3 = str3.Substring(0, str3.LastIndexOf(@"\"));
         dbpath = str3;
         path = str3 + @"\JSDiskDLL.dll";
         if (File.Exists(path))
         {
             goto Label_00E9;
         }
         string fileName = "";
         for (int i = 0; i < subKeyNames.Length; i++)
         {
             str5 = Path.Combine(key.OpenSubKey(subKeyNames[i]).GetValue("Path") as string, @"Bin\JSDiskDLL.dll");
             if (File.Exists(str5))
             {
                 goto Label_00C5;
             }
         }
         goto Label_00C9;
     Label_00C5:
         fileName = str5;
     Label_00C9:
         if (fileName != "")
         {
             new FileInfo(fileName).CopyTo(path);
         }
     Label_00E9:
         if ((path == "") || !File.Exists(path))
         {
             goto Label_0346;
         }
         int realTaxCode = -1;
         int kpNo = -1;
         int areaCode = -1;
         string name = "";
         byte[] taxcode = new byte[0x19];
         realTaxCode = GetRealTaxCode(taxcode, Encoding.GetEncoding("GB18030").GetBytes(path));
         string oldTaxcode = Encoding.GetEncoding("GB18030").GetString(taxcode).Trim(new char[1]);
         if (((oldTaxcode == null) || (oldTaxcode == "")) || (realTaxCode != 0))
         {
             goto Label_033E;
         }
         byte[] machineno = new byte[5];
         kpNo = GetKpNo(machineno, Encoding.GetEncoding("GB18030").GetBytes(path));
         string str8 = Encoding.GetEncoding("GB18030").GetString(machineno).Trim(new char[1]);
         if (((str8 == null) || (str8 == "")) || (kpNo != 0))
         {
             return;
         }
         byte[] areacode = new byte[0x19];
         areaCode = GetAreaCode(areacode, Encoding.GetEncoding("GB18030").GetBytes(path));
         string str9 = Encoding.GetEncoding("GB18030").GetString(areacode).Trim(new char[1]);
         if (((str9 == null) || (str9 == "")) || (areaCode != 0))
         {
             goto Label_0334;
         }
         foreach (string str10 in subKeyNames)
         {
             if (str10 == (oldTaxcode + "." + str8))
             {
                 name = str10;
                 break;
             }
         }
         goto Label_0276;
     Label_0276:
         if (name == "")
         {
             key.Close();
         }
         else
         {
             RegistryKey key3 = key.OpenSubKey(name, true);
             string str11 = key3.GetValue("orgcode", "") as string;
             if (str11 != str9)
             {
                 key3.SetValue("orgcode", str9);
                 key3.Close();
                 key.Close();
                 string str12 = dbpath;
                 dbpath = str12 + @"\" + oldTaxcode + "." + str8 + @"\bin\cc3268.dll";
                 this.UpdateBSZT(oldTaxcode, dbpath, oldTaxcode);
             }
             else
             {
                 key3.Close();
                 key.Close();
             }
         }
         return;
     Label_0334:
         key.Close();
         return;
     Label_033E:
         key.Close();
         return;
     Label_0346:
         key.Close();
         return;
     Label_034E:
         key.Close();
     }
     catch (Exception)
     {
     }
 }
Example #50
0
        private static async Task SendChat(SettingBussines clsSetting, SimcardBussines simCard)
        {
            try
            {
                var passage1 = new List <string>();
                if (!string.IsNullOrEmpty(simCard.FirstChatPassage))
                {
                    passage1.Add(simCard.FirstChatPassage);
                }
                if (!string.IsNullOrEmpty(simCard.FirstChatPassage2))
                {
                    passage1.Add(simCard.FirstChatPassage2);
                }
                if (!string.IsNullOrEmpty(simCard.FirstChatPassage3))
                {
                    passage1.Add(simCard.FirstChatPassage3);
                }
                if (!string.IsNullOrEmpty(simCard.FirstChatPassage4))
                {
                    passage1.Add(simCard.FirstChatPassage4);
                }
                var passage2 = new List <string>();
                if (!string.IsNullOrEmpty(simCard.SecondChatPassage))
                {
                    passage2.Add(simCard.SecondChatPassage);
                }
                if (!string.IsNullOrEmpty(simCard.SecondChatPassage2))
                {
                    passage2.Add(simCard.SecondChatPassage2);
                }
                if (!string.IsNullOrEmpty(simCard.SecondChatPassage3))
                {
                    passage2.Add(simCard.SecondChatPassage3);
                }
                if (!string.IsNullOrEmpty(simCard.SecondChatPassage4))
                {
                    passage2.Add(simCard.SecondChatPassage4);
                }
                var date = DateConvertor.M2SH(DateTime.Now);
                date = date.Replace("/", "_");
                if (simCard.IsSendChat)
                {
                    var city = DivarCityBussines.GetAsync(simCard.DivarCityForChat);

                    var cat1 = AdvCategoryBussines.Get(simCard.DivarChatCat1)?.Name ?? "";
                    var cat2 = AdvCategoryBussines.Get(simCard.DivarChatCat2)?.Name ?? "";
                    var cat3 = AdvCategoryBussines.Get(simCard.DivarChatCat3)?.Name ?? "";

                    var fileName = $"{cat1}__{cat2}__{cat3}__{date}";
                    fileName = fileName.Replace(" ", "_");
                    var ff    = Path.Combine(clsSetting.Address, fileName + ".txt");
                    var divar = await DivarAdv.GetInstance();

                    await divar.SendChat(passage1, passage2, simCard.ChatCount, city.Name, cat1, cat2, cat3,
                                         ff, simCard);
                }

                //if (simCard.IsSendChatSheypoor)
                //{
                //    var city1 = SheypoorCityBussines.GetAsync(simCard.SheypoorCityForChat);

                //    var cat1 = AdvCategoryBussines.Get(simCard.SheypoorChatCat1)?.Name ?? "";
                //    var cat2 = AdvCategoryBussines.Get(simCard.SheypoorChatCat2)?.Name ?? "";
                //    var fileName = $"{cat1}__{cat2}__{date}";
                //    var ff = Path.Combine(clsSetting.Address, fileName + ".txt");

                //    var shey = await SheypoorAdv.GetInstance();
                //    await shey.SendChat(passage1, passage2, simCard.ChatCount, city1.Name, cat1, cat2, null,
                //        ff, simCard);
                //}

                simCard.NextUse = DateTime.Now.AddMinutes(30);
                await simCard.SaveAsync();
            }
            catch (Exception e)
            {
                WebErrorLog.ErrorInstence.StartErrorLog(e);
            }
        }
Example #51
0
		private void AttachFeatures()
		{
			this.sensorServer = new SensorServer(this.xmppClient, true);
			this.sensorServer.OnExecuteReadoutRequest += (sender, e) =>
			{
				try
				{
					Log.Informational("Performing readout.", this.xmppClient.BareJID, e.Actor);

					List<Field> Fields = new List<Field>();
					DateTime Now = DateTime.Now;

					if (e.IsIncluded(FieldType.Identity))
					{
						Fields.Add(new StringField(ThingReference.Empty, Now, "Device ID", this.deviceId, FieldType.Identity, FieldQoS.AutomaticReadout));

						if (!string.IsNullOrEmpty(this.sensorJid))
						{
							Fields.Add(new StringField(ThingReference.Empty, Now, "Sensor, JID", this.sensorJid, FieldType.Identity, FieldQoS.AutomaticReadout));

							if (this.sensor != null)
							{
								if (!string.IsNullOrEmpty(this.sensor.NodeId))
									Fields.Add(new StringField(ThingReference.Empty, Now, "Sensor, Node ID", this.sensor.NodeId, FieldType.Identity, FieldQoS.AutomaticReadout));

								if (!string.IsNullOrEmpty(this.sensor.SourceId))
									Fields.Add(new StringField(ThingReference.Empty, Now, "Sensor, Source ID", this.sensor.SourceId, FieldType.Identity, FieldQoS.AutomaticReadout));

								if (!string.IsNullOrEmpty(this.sensor.Partition))
									Fields.Add(new StringField(ThingReference.Empty, Now, "Sensor, Partition", this.sensor.Partition, FieldType.Identity, FieldQoS.AutomaticReadout));
							}
						}

						if (!string.IsNullOrEmpty(this.actuatorJid))
						{
							Fields.Add(new StringField(ThingReference.Empty, Now, "Actuator, JID", this.actuatorJid, FieldType.Identity, FieldQoS.AutomaticReadout));

							if (this.actuator != null)
							{
								if (!string.IsNullOrEmpty(this.actuator.NodeId))
									Fields.Add(new StringField(ThingReference.Empty, Now, "Actuator, Node ID", this.actuator.NodeId, FieldType.Identity, FieldQoS.AutomaticReadout));

								if (!string.IsNullOrEmpty(this.actuator.SourceId))
									Fields.Add(new StringField(ThingReference.Empty, Now, "Actuator, Source ID", this.actuator.SourceId, FieldType.Identity, FieldQoS.AutomaticReadout));

								if (!string.IsNullOrEmpty(this.actuator.Partition))
									Fields.Add(new StringField(ThingReference.Empty, Now, "Actuator, Partition", this.actuator.Partition, FieldType.Identity, FieldQoS.AutomaticReadout));
							}
						}
					}

					if (e.IsIncluded(FieldType.Status))
					{
						RosterItem Item;

						if (string.IsNullOrEmpty(this.sensorJid))
							Fields.Add(new StringField(ThingReference.Empty, Now, "Sensor, Availability", "Not Found", FieldType.Status, FieldQoS.AutomaticReadout));
						else
						{
							Item = this.xmppClient[this.sensorJid];
							if (Item is null)
								Fields.Add(new StringField(ThingReference.Empty, Now, "Sensor, Availability", "Not Found", FieldType.Status, FieldQoS.AutomaticReadout));
							else if (!Item.HasLastPresence)
								Fields.Add(new StringField(ThingReference.Empty, Now, "Sensor, Availability", "Offline", FieldType.Status, FieldQoS.AutomaticReadout));
							else
								Fields.Add(new StringField(ThingReference.Empty, Now, "Sensor, Availability", Item.LastPresence.Availability.ToString(), FieldType.Status, FieldQoS.AutomaticReadout));
						}

						if (string.IsNullOrEmpty(this.actuatorJid))
							Fields.Add(new StringField(ThingReference.Empty, Now, "Actuator, Availability", "Not Found", FieldType.Status, FieldQoS.AutomaticReadout));
						else
						{
							Item = this.xmppClient[this.actuatorJid];
							if (Item is null)
								Fields.Add(new StringField(ThingReference.Empty, Now, "Actuator, Availability", "Not Found", FieldType.Status, FieldQoS.AutomaticReadout));
							else if (!Item.HasLastPresence)
								Fields.Add(new StringField(ThingReference.Empty, Now, "Actuator, Availability", "Offline", FieldType.Status, FieldQoS.AutomaticReadout));
							else
								Fields.Add(new StringField(ThingReference.Empty, Now, "Actuator, Availability", Item.LastPresence.Availability.ToString(), FieldType.Status, FieldQoS.AutomaticReadout));
						}
					}

					if (e.IsIncluded(FieldType.Momentary))
					{
						if (this.light.HasValue)
							Fields.Add(new QuantityField(ThingReference.Empty, Now, "Light", this.light.Value, 2, "%", FieldType.Momentary, FieldQoS.AutomaticReadout));

						if (this.motion.HasValue)
							Fields.Add(new BooleanField(ThingReference.Empty, Now, "Motion", this.motion.Value, FieldType.Momentary, FieldQoS.AutomaticReadout));

						if (this.output.HasValue)
							Fields.Add(new BooleanField(ThingReference.Empty, Now, "Output", this.output.Value, FieldType.Momentary, FieldQoS.AutomaticReadout));
					}

					e.ReportFields(true, Fields);
				}
				catch (Exception ex)
				{
					e.ReportErrors(true, new ThingError(ThingReference.Empty, ex.Message));
				}

				return Task.CompletedTask;
			};

			this.xmppClient.OnError += (Sender, ex) =>
			{
				Log.Error(ex);
				return Task.CompletedTask;
			};

			this.xmppClient.OnPasswordChanged += (Sender, e) =>
			{
				Log.Informational("Password changed.", this.xmppClient.BareJID);
			};

			this.xmppClient.OnPresenceSubscribe += (Sender, e) =>
			{
				Log.Informational("Accepting friendship request.", this.xmppClient.BareJID, e.From);
				e.Accept();
				return Task.CompletedTask;
			};

			this.xmppClient.OnPresenceUnsubscribe += (Sender, e) =>
			{
				Log.Informational("Friendship removed.", this.xmppClient.BareJID, e.From);
				e.Accept();
				return Task.CompletedTask;
			};

			this.xmppClient.OnPresenceSubscribed += (Sender, e) =>
			{
				Log.Informational("Friendship request accepted.", this.xmppClient.BareJID, e.From);

				if (string.Compare(e.FromBareJID, this.sensorJid, true) == 0)
					this.SubscribeToSensorData();

				return Task.CompletedTask;
			};

			this.xmppClient.OnPresenceUnsubscribed += (Sender, e) =>
			{
				Log.Informational("Friendship removal accepted.", this.xmppClient.BareJID, e.From);
				return Task.CompletedTask;
			};

			this.xmppClient.OnPresence += XmppClient_OnPresence;

			this.bobClient = new BobClient(this.xmppClient, Path.Combine(Path.GetTempPath(), "BitsOfBinary"));
			this.chatServer = new ChatServer(this.xmppClient, this.bobClient, this.sensorServer);

			// XEP-0054: vcard-temp: http://xmpp.org/extensions/xep-0054.html
			this.xmppClient.RegisterIqGetHandler("vCard", "vcard-temp", this.QueryVCardHandler, true);

			this.sensorClient = new SensorClient(this.xmppClient);
			this.controlClient = new ControlClient(this.xmppClient);
		}
Example #52
0
 public void HandleSZHY()
 {
     try
     {
         string str6;
         RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\fwkp.exe", true);
         string[] subKeyNames = key.GetSubKeyNames();
         if ((subKeyNames == null) || (subKeyNames.Length < 1))
         {
             goto Label_0725;
         }
         string path = "";
         string str2 = key.GetValue("Path", "") as string;
         string dbpath = "";
         str2 = str2.Substring(0, str2.LastIndexOf(@"\"));
         dbpath = str2;
         path = str2 + @"\JSDiskDLL.dll";
         string str4 = str2 + @"\temp";
         if (!Directory.Exists(str4))
         {
             Directory.CreateDirectory(str4);
         }
         DirectoryInfo info = new DirectoryInfo(str4) {
             Attributes = FileAttributes.Hidden
         };
         FileInfo[] files = info.GetFiles();
         try
         {
             foreach (FileInfo info2 in files)
             {
                 info2.Delete();
             }
         }
         catch (Exception)
         {
         }
         if (File.Exists(path))
         {
             goto Label_0147;
         }
         string fileName = "";
         for (int i = 0; i < subKeyNames.Length; i++)
         {
             str6 = Path.Combine(key.OpenSubKey(subKeyNames[i]).GetValue("Path") as string, @"Bin\JSDiskDLL.dll");
             if (File.Exists(str6))
             {
                 goto Label_0123;
             }
         }
         goto Label_0127;
     Label_0123:
         fileName = str6;
     Label_0127:
         if (fileName != "")
         {
             new FileInfo(fileName).CopyTo(path);
         }
     Label_0147:
         if ((path == "") || !File.Exists(path))
         {
             goto Label_071D;
         }
         byte[] oldtaxcode = new byte[0x19];
         int oldTaxCode = GetOldTaxCode(oldtaxcode, Encoding.GetEncoding("GB18030").GetBytes(path));
         string oldTaxcode = Encoding.GetEncoding("GB18030").GetString(oldtaxcode).Trim(new char[1]);
         if (((oldTaxCode != 0) || (oldTaxcode == null)) || (oldTaxcode.Trim() == ""))
         {
             goto Label_0715;
         }
         byte[] taxcode = new byte[0x19];
         int realTaxCode = GetRealTaxCode(taxcode, Encoding.GetEncoding("GB18030").GetBytes(path));
         string newTaxcode = Encoding.GetEncoding("GB18030").GetString(taxcode).Trim(new char[1]);
         if (((realTaxCode != 0) || (newTaxcode == null)) || (newTaxcode.Trim() == ""))
         {
             goto Label_070D;
         }
         byte[] machineno = new byte[5];
         int kpNo = GetKpNo(machineno, Encoding.GetEncoding("GB18030").GetBytes(path));
         string str9 = Encoding.GetEncoding("GB18030").GetString(machineno).Trim(new char[1]);
         if (((kpNo != 0) || (str9 == null)) || (str9.Trim() == ""))
         {
             goto Label_0705;
         }
         byte[] areacode = new byte[5];
         int areaCode = GetAreaCode(areacode, Encoding.GetEncoding("GB18030").GetBytes(path));
         string str10 = Encoding.GetEncoding("GB18030").GetString(areacode).Trim(new char[1]);
         if (((areaCode != 0) || (str10 == null)) || (str10.Trim() == ""))
         {
             goto Label_06FD;
         }
         string oldFolderName = "";
         for (int j = 0; j < subKeyNames.Length; j++)
         {
             if (subKeyNames[j].Equals(newTaxcode + "." + str9))
             {
                 goto Label_06F5;
             }
             if (subKeyNames[j].Equals(oldTaxcode + "." + str9))
             {
                 oldFolderName = subKeyNames[j];
             }
         }
         if (oldFolderName == "")
         {
             key.Close();
         }
         else
         {
             this.CheckAndMoveNecessaryDll(oldFolderName);
             RegistryKey key3 = key.OpenSubKey(oldFolderName);
             string str12 = Path.Combine(key3.GetValue("Path") as string, @"Bin\AddedRealTax.dll");
             if (File.Exists(str12))
             {
                 new FileInfo(str12).CopyTo(str4 + @"\AddedRealTax.dll");
                 string code = oldTaxcode;
                 if (oldTaxcode.Length < 15)
                 {
                     for (int k = 0; k < (15 - oldTaxcode.Length); k++)
                     {
                         code = code + "0";
                     }
                 }
                 string str14 = newTaxcode;
                 if (newTaxcode.Length < 15)
                 {
                     for (int m = 0; m < (15 - newTaxcode.Length); m++)
                     {
                         str14 = str14 + "0";
                     }
                 }
                 FileCryptEx(1, str4 + @"\AddedRealTax.dll", code);
                 FileCryptEx(2, str4 + @"\AddedRealTax.dll", str14);
                 new FileInfo(str4 + @"\AddedRealTax.dll").CopyTo(str12, true);
                 string str15 = key3.GetValue("Path", "") as string;
                 string destDirName = str15.Replace(oldFolderName, newTaxcode + "." + str9);
                 new DirectoryInfo(str15).MoveTo(destDirName);
                 string str17 = key3.GetValue("", "") as string;
                 str17 = str17.Replace(oldFolderName, newTaxcode + "." + str9);
                 string str18 = newTaxcode;
                 string str19 = key3.GetValue("DataBaseVersion", "") as string;
                 string str20 = str9;
                 key3.GetValue("orgcode", "");
                 string str21 = key3.GetValue("Version", "") as string;
                 key3.Close();
                 key3 = null;
                 key.DeleteSubKey(oldFolderName);
                 key3 = key.CreateSubKey(newTaxcode + "." + str9, RegistryKeyPermissionCheck.ReadWriteSubTree);
                 key.SetValue("", str17);
                 key.SetValue("code", str18);
                 key.SetValue("machine", str20);
                 key.SetValue("DataBaseVersion", str19);
                 key.SetValue("orgcode", str10);
                 key.SetValue("Path", destDirName);
                 key.SetValue("Version", str21);
                 key3.SetValue("", str17);
                 key3.SetValue("code", str18);
                 key3.SetValue("machine", str20);
                 key3.SetValue("DataBaseVersion", str19);
                 key3.SetValue("orgcode", str10);
                 key3.SetValue("Path", destDirName);
                 key3.SetValue("Version", str21);
                 string str22 = dbpath;
                 dbpath = str22 + @"\" + newTaxcode + "." + str9 + @"\bin\cc3268.dll";
                 this.UpdateBSZT(oldTaxcode, dbpath, newTaxcode);
                 info.Delete(true);
                 this.SaveNewOldTaxCode(newTaxcode, oldTaxcode);
                 this.ChageUninstallInfo(newTaxcode + "." + str9, oldFolderName, Path.Combine(key3.GetValue("Path") as string, "Uninstall.dat"));
                 key3.Close();
                 key.Close();
                 this.ExcuteZJDllBat(str2 + @"\" + newTaxcode + "." + str9);
             }
         }
         return;
     Label_06F5:
         key.Close();
         return;
     Label_06FD:
         key.Close();
         return;
     Label_0705:
         key.Close();
         return;
     Label_070D:
         key.Close();
         return;
     Label_0715:
         key.Close();
         return;
     Label_071D:
         key.Close();
         return;
     Label_0725:
         key.Close();
     }
     catch (Exception exception)
     {
         MessageBox.Show("【税控发票开票软件(金税盘版)】一体化变更异常:" + exception.Message, "异常");
     }
 }
 public string ResolvePath(long projectId, string bookVersionExternalId, string fileName)
 {
     return Path.Combine(projectId.ToString(), bookVersionExternalId, fileName);
 }
Example #54
0
 private bool CheckPath(string path)
 {
     return File.Exists(Path.Combine(path, "osu!.db"));
 }
Example #55
0
 private void addmusicbtn_Click(object sender, EventArgs e)
 {
     using (OpenFileDialog dlgOpen = new OpenFileDialog())
     {
         dlgOpen.Filter      = "MP4 File|*.mp4";
         dlgOpen.Title       = "Select Audio File";
         dlgOpen.Multiselect = true;
         if (dlgOpen.ShowDialog() == DialogResult.OK)
         {
             UnlockDirectory(username);
             for (int i = 0; i < dlgOpen.FileNames.Length; i++)
             {
                 FileInfo checkexist = new FileInfo($"C:\\Users\\{username}\\System\\" + dlgOpen.SafeFileNames[i]);
                 if (!checkexist.Exists)
                 {
                     if (musiclist2.Items.Count > 0)
                     {
                         for (int a = 0; a < musiclist2.Items.Count; a++)
                         {
                             if (CalculateSimilarity(dlgOpen.SafeFileNames[i], musiclist2.Items[i].Text) < 0.35)
                             {
                                 File.SetAttributes(dlgOpen.FileNames[i], File.GetAttributes(dlgOpen.FileNames[i]) | FileAttributes.Hidden);
                                 File.Move(dlgOpen.FileNames[i], $"C:\\Users\\{username}\\System\\" + dlgOpen.SafeFileNames[i]);
                                 break;
                             }
                         }
                     }
                     else
                     {
                         File.SetAttributes(dlgOpen.FileNames[i], File.GetAttributes(dlgOpen.FileNames[i]) | FileAttributes.Hidden);
                         File.Move(dlgOpen.FileNames[i], $"C:\\Users\\{username}\\System\\" + dlgOpen.SafeFileNames[i]);
                     }
                 }
                 else
                 {
                     MessageBox.Show("재생목록에 있는 노래입니다.");
                 }
             }
             musiclist2.Items.Clear();
             // 재생목록 불러오기
             var           route = $"C:\\Users\\{username}\\System\\";
             DirectoryInfo dir   = new DirectoryInfo(route);
             if (dir.Exists)
             {
                 try
                 {
                     string[] files = Directory.GetFiles(route);
                     foreach (string s in files)
                     {
                         string filename      = Path.GetFileName(s);
                         string Full          = route + filename;
                         string finalfilename = "";
                         if (filename.Length > 60)
                         {
                             for (int i = 0; i < filename.Length / 2; i++)
                             {
                                 finalfilename += filename[i];
                             }
                             finalfilename += "· · ·.mp3";
                         }
                         else
                         {
                             finalfilename = filename;
                         }
                         musiclist2.Items.Add(Full, finalfilename, 0);
                     }
                     if (musiclist2.Items.Count > 0)
                     {
                         fileName = musiclist2.Items[0].Name;
                         CurrentAudioFile(fileName);
                         metroTabControl1.SelectedIndex = 1;
                     }
                 }
                 catch
                 {
                     MessageBox.Show("플레이리스트를 불러오는데 실패했습니다.");
                 }
                 LockDirectory(username);
             }
         }
     }
 }
 public void LoadState()
 {
     string caminho = Path.Combine(Application.persistentDataPath, "savegame.dat");
     string texto = File.ReadAllText(caminho);
     save = JsonUtility.FromJson<SaveGame>(texto);
 }
Example #57
0
 public MainForm()
 {
     try
     {
         //폼로드
         InitializeComponent();
         //최대화버튼 없애기
         this.MaximizeBox = false;
         //유저이름가져오기
         username = Environment.UserName;
         //구버전 경로 확인
         CheckOldPath($"C:\\Users\\{username}\\YouTubeMp3\\");
         //불륨셋팅
         Win32.SetSoundVolume(1);
         //탭인덱스 바꾸기
         metroTabControl1.SelectedIndex = 0;
         //불륨 레지스트리
         reg = Registry.LocalMachine.CreateSubKey("Software").CreateSubKey("MusicVolume");
         if (reg.GetValue("VOLUME", null) != null)
         {
             volumtrackbar.Value = Convert.ToInt32(reg.GetValue("VOLUME"));
             soundvaluetext.Text = reg.GetValue("VOLUME").ToString();
         }
         //musiclist 설정
         musiclist.View        = View.Details;
         musiclist.HeaderStyle = ColumnHeaderStyle.None;
         ColumnHeader h = new ColumnHeader();
         h.Width = musiclist.ClientSize.Width - SystemInformation.VerticalScrollBarWidth;
         musiclist.Columns.Add(h);
         //musiclist2 설정
         musiclist2.View        = View.Details;
         musiclist2.HeaderStyle = ColumnHeaderStyle.None;
         ColumnHeader h2 = new ColumnHeader();
         h2.Width = musiclist2.ClientSize.Width - SystemInformation.VerticalScrollBarWidth;
         musiclist2.Columns.Add(h2);
         //재생목록 불러오기
         var           route = $"C:\\Users\\{username}\\System\\";
         DirectoryInfo dir   = new DirectoryInfo(route);
         if (dir.Exists)
         {
             UnlockDirectory(username);
             try
             {
                 string[] files = Directory.GetFiles(route);
                 foreach (string s in files)
                 {
                     string filename      = Path.GetFileName(s);
                     string Full          = route + filename;
                     string finalfilename = "";
                     if (filename.Length > 60)
                     {
                         for (int i = 0; i < filename.Length / 2; i++)
                         {
                             finalfilename += filename[i];
                         }
                         finalfilename += "· · ·.mp3";
                     }
                     else
                     {
                         finalfilename = filename;
                     }
                     musiclist2.Items.Add(Full, finalfilename, 0);
                 }
                 if (musiclist2.Items.Count > 0)
                 {
                     fileName = musiclist2.Items[0].Name;
                     CurrentAudioFile(fileName);
                     metroTabControl1.SelectedIndex = 1;
                 }
             }
             catch (Exception a)
             {
                 MessageBox.Show("플레이리스트를 불러오는데 실패했습니다." + a.ToString());
             }
             LockDirectory(username);
             ShowPopularSong();
         }
     }
     catch
     {
         MessageBox.Show("오류 발생 프로그램을 종료합니다.");
         Process.GetCurrentProcess().Kill();
     }
 }
Example #58
0
 protected UpdateDb()
 {
     mDataFile = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase.Substring(8)), "data.sdf");
     mConnectionString = string.Format("Data Source = \"{0}\"", mDataFile);
 }
        protected override void DoExport()
        {
            EditorUtility.ClearProgressBar();
            BridgeExport.isProcessing = false;

            List <string> allRecursiveAssets = new List <string>();

            // string choosedPath = GetExportPath();
            // string savePath = Path.Combine(choosedPath, "Assets/");
            var savePath = Path.Combine(ExportStore.storagePath, "Assets/");

            updateRecourcesDir();

            int totalCount = 0;

            string [] arr_dir = dirs.ToArray();

            JSONObject jsonConfig = new JSONObject(JSONObject.Type.ARRAY);

            if (arr_dir.Length > 0)
            {
                for (int index = 0; index < supportedTypes.Length; index++)
                {
                    string   filter = "t:" + supportedTypes[index];
                    string[] guids  = AssetDatabase.FindAssets(filter, arr_dir);
                    // Debug.Log(guids.Length);
                    if (guids.Length == 0)
                    {
                        continue;
                    }

                    JSONObject category = new JSONObject(JSONObject.Type.OBJECT);
                    JSONObject data     = new JSONObject(JSONObject.Type.ARRAY);
                    category.AddField("type", supportedTypes[index]);
                    category.AddField("files", data);

                    var t = 0;
                    HashSet <string> setFiles = new HashSet <string>();
                    for (int i = 0; i < guids.Length; i++)
                    {
                        string path = AssetDatabase.GUIDToAssetPath(guids[i]);
                        if (path.StartsWith("Assets"))
                        {
                            path = path.Substring(6);
                        }
                        string absolutePath = Path.Combine(Application.dataPath, path);
                        // #if UNITY_EDITOR_WIN
                        // string absolutePath = Application.dataPath + "\\" + path;
                        // #else
                        // string absolutePath = Application.dataPath + "/" + path;
                        // #endif

                        // string filename = System.IO.Path.GetFileName(absolutePath);

                        string copyToPath = Path.Combine(savePath, path);
                        // #if UNITY_EDITOR_WIN
                        // string copyToPath = savePath + "\\" + path;
                        // #else
                        // string copyToPath = savePath + "/" + path;
                        // #endif

                        string extension = System.IO.Path.GetExtension(path);
                        if (setExclude.Contains(extension))
                        {
                            continue;
                        }

                        if (supportedTypes[index] != "GameObject")
                        {
                            #if USE_RAW_MODE
                            string        projpath    = "Assets" + path;
                            WXRawResource rawResource = new WXRawResource(projpath);
                            string        ret_path    = rawResource.Export(this);
                            allRecursiveAssets.Add(ret_path);
                            #else
                            wxFileUtil.CopyFile(absolutePath, copyToPath);
                            #endif
                        }

                        JSONObject fileInfo = new JSONObject(JSONObject.Type.OBJECT);
                        // fileInfo.AddField("key", Path.GetFileNameWithoutExtension(filename));
                        string key = getResourcePath(path);
                        if (setFiles.Contains(key))
                        {
                            continue;
                        }
                        else
                        {
                            setFiles.Add(key);
                        }
                        fileInfo.AddField("key", key);
                        fileInfo.AddField("name", "Assets" + path);
                        data.Add(fileInfo);
                        totalCount++;
                        EditorUtility.DisplayProgressBar("原始资源导出", "", t++ / guids.Length);
                    }
                    jsonConfig.Add(category);
                }
            }
            #if USE_RAW_MODE
            string tempConfigFile = Path.Combine(Application.dataPath, "Resources.json");
            wxFileUtil.SaveJsonFile(jsonConfig, tempConfigFile);
            string        configpath   = "Assets/Resources.json";
            WXRawResource rawConfig    = new WXRawResource(configpath);
            string        ret_cfg_path = rawConfig.Export(this);
            allRecursiveAssets.Add(ret_cfg_path);
            File.Delete(tempConfigFile);
            #endif
            // string content = jsonConfig.ToString();
            // ExportStore.AddTextFile(configpath, content, WXUtility.GetMD5FromString(content));
            // List<string> useConfig = new List<string>();
            // useConfig.Add(configpath);
            // ExportStore.AddResource(configpath, "raw", null, useConfig);
            // allRecursiveAssets.Add(configpath);


            ExportStore.GenerateResourcePackage(
                "WXResources",
                allRecursiveAssets
                );

            EditorUtility.ClearProgressBar();
            Debug.Log("导出成功,总共导出文件个数:" + totalCount);
        }
Example #60
0
 private string getFileName(string filePath)
 {
     return(Path.GetFileName(filePath));
 }