Inheritance: MonoBehaviour
Example #1
0
        static void Main(string[] args)
        {
            Component fileSystem = new Directory("Файловая система");
            // определяем новый диск
            Component diskC = new Directory("Диск С");
            // новые файлы
            Component pngFile = new File("12345.png");
            Component docxFile = new File("Document.docx");
            // добавляем файлы на диск С
            diskC.Add(pngFile);
            diskC.Add(docxFile);
            // добавляем диск С в файловую систему
            fileSystem.Add(diskC);
            // выводим все данные
            fileSystem.Print();
            Console.WriteLine();
            // удаляем с диска С файл
            diskC.Remove(pngFile);
            // создаем новую папку
            Component docsFolder = new Directory("Мои Документы");
            // добавляем в нее файлы
            Component txtFile = new File("readme.txt");
            Component csFile = new File("Program.cs");
            docsFolder.Add(txtFile);
            docsFolder.Add(csFile);
            diskC.Add(docsFolder);

            fileSystem.Print();

            Console.Read();
        }
 public override void SetUp()
 {
     base.SetUp();
     INDEX_SIZE = AtLeast(2000);
     Index = NewDirectory();
     RandomIndexWriter writer = new RandomIndexWriter(Random(), Index);
     RandomGen random = new RandomGen(this, Random());
     for (int i = 0; i < INDEX_SIZE; ++i) // don't decrease; if to low the
     {
         // problem doesn't show up
         Document doc = new Document();
         if ((i % 5) != 0) // some documents must not have an entry in the first
         {
             // sort field
             doc.Add(NewStringField("publicationDate_", random.LuceneDate, Field.Store.YES));
         }
         if ((i % 7) == 0) // some documents to match the query (see below)
         {
             doc.Add(NewTextField("content", "test", Field.Store.YES));
         }
         // every document has a defined 'mandant' field
         doc.Add(NewStringField("mandant", Convert.ToString(i % 3), Field.Store.YES));
         writer.AddDocument(doc);
     }
     Reader = writer.Reader;
     writer.Dispose();
     Query = new TermQuery(new Term("content", "test"));
 }
 internal Lucene40DocValuesReader(SegmentReadState state, string filename, string legacyKey)
 {
     this.State = state;
     this.LegacyKey = legacyKey;
     this.Dir = new CompoundFileDirectory(state.Directory, filename, state.Context, false);
     RamBytesUsed_Renamed = new AtomicLong(RamUsageEstimator.ShallowSizeOf(this.GetType()));
 }
 public override void SetUp()
 {
     base.SetUp();
     DirectoryInfo file = CreateTempDir("testIndex");
     // use a simple FSDir here, to be sure to have SimpleFSInputs
     Dir = new SimpleFSDirectory(file, null);
 }
        public void BeforeClass()
        {
            Directory = NewDirectory();
            RandomIndexWriter writer = new RandomIndexWriter(Random(), Directory, Similarity, TimeZone);

            Document doc = new Document();
            Field field = NewStringField(FIELD, "meaninglessnames", Field.Store.NO);
            doc.Add(field);

            for (int i = 0; i < 5137; ++i)
            {
                writer.AddDocument(doc);
            }

            field.StringValue = "tangfulin";
            writer.AddDocument(doc);

            field.StringValue = "meaninglessnames";
            for (int i = 5138; i < 11377; ++i)
            {
                writer.AddDocument(doc);
            }

            field.StringValue = "tangfulin";
            writer.AddDocument(doc);

            Reader = writer.Reader;
            Searcher = NewSearcher(Reader);
            writer.Dispose();
        }
Example #6
0
        public Directory ListDirectoryContents(string url)
        {
            Directory dirToReturn = new Directory();
             List<string> listOfItems;
             listOfItems = RetrieveAllItems(url);

            foreach (string item in listOfItems)
            {
                //if there is no extension found we assume this is a dir
                if (System.IO.Path.HasExtension(item) == false)
                {
                    Directory newDir = ListDirectoryContents(url + item + "/");
                    newDir.url = item;
                    dirToReturn.dirs.Add(newDir);

                }
                //if there is an extension we creat a new file object
                else if (System.IO.Path.HasExtension(item) == true)
                {
                    File newFile = new File();
                    newFile.url = item;
                    dirToReturn.files.Add(newFile);
                }
            }
            return dirToReturn;
        }
 public override void TearDown()
 {
     Reader.Dispose();
     MDirectory.Dispose();
     MDirectory = null;
     base.TearDown();
 }
        public override void SetUp()
        {
            base.SetUp();
            Dir = NewDirectory();
            FieldName = Random().NextBoolean() ? "field" : ""; // sometimes use an empty string as field name
            RandomIndexWriter writer = new RandomIndexWriter(Random(), Dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random(), MockTokenizer.KEYWORD, false)).SetMaxBufferedDocs(TestUtil.NextInt(Random(), 50, 1000)));
            Document doc = new Document();
            Field field = NewStringField(FieldName, "", Field.Store.NO);
            doc.Add(field);
            List<string> terms = new List<string>();
            int num = AtLeast(200);
            for (int i = 0; i < num; i++)
            {
                string s = TestUtil.RandomUnicodeString(Random());
                field.StringValue = s;
                terms.Add(s);
                writer.AddDocument(doc);
            }

            if (VERBOSE)
            {
                // utf16 order
                terms.Sort();
                Console.WriteLine("UTF16 order:");
                foreach (string s in terms)
                {
                    Console.WriteLine("  " + UnicodeUtil.ToHexString(s));
                }
            }

            Reader = writer.Reader;
            Searcher1 = NewSearcher(Reader);
            Searcher2 = NewSearcher(Reader);
            writer.Dispose();
        }
        public TemporaryLocalDirectory(Directory backingDirectory)
        {
            UnderlyingDirectory = backingDirectory;

            if (!UnderlyingDirectory.Exists())
                UnderlyingDirectory.Create();
        }
Example #10
0
        public void debugMode()
        {
            //初始化全局块组
            for (int i = 0; i < Config.GROUPS; i++)
                VFS.BLOCK_GROUPS[i] = new BlockGroup(i);

            //初始化目录树
            VFS.rootDir = new Directory("/", null);

            Directory bootDir = new Directory("boot", VFS.rootDir);
            Directory etcDir = new Directory("etc", VFS.rootDir);
            Directory libDir = new Directory("lib", VFS.rootDir);
            Directory homeDir = new Directory("home", VFS.rootDir);
            Directory rootDir = new Directory("root", VFS.rootDir);
            Directory tempDir = new Directory("temp", VFS.rootDir);
            VFS.rootDir.add(bootDir);
            VFS.rootDir.add(etcDir);
            VFS.rootDir.add(homeDir);
            VFS.rootDir.add(libDir);
            VFS.rootDir.add(rootDir);
            VFS.rootDir.add(tempDir);

            File file1 = new File("bashrc", etcDir);
            File file2 = new File("shadowsocks", etcDir);
            etcDir.add(file1);
            etcDir.add(file2);
        }
 public override void SetUp()
 {
     base.SetUp();
     Dir = NewDirectory();
     DocHelper.SetupDoc(TestDoc);
     Info = DocHelper.WriteDoc(Random(), Dir, TestDoc);
 }
Example #12
0
        public override void SetUp()
        {
            base.SetUp();
            // we generate aweful regexps: good for testing.
            // but for preflex codec, the test can be very slow, so use less iterations.
            NumIterations = Codec.Default.Name.Equals("Lucene3x") ? 10 * RANDOM_MULTIPLIER : AtLeast(50);
            Dir = NewDirectory();
            RandomIndexWriter writer = new RandomIndexWriter(Random(), Dir, (IndexWriterConfig)NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random(), MockTokenizer.KEYWORD, false)).SetMaxBufferedDocs(TestUtil.NextInt(Random(), 50, 1000)));
            Document doc = new Document();
            Field field = NewStringField("field", "", Field.Store.YES);
            doc.Add(field);
            Terms = new SortedSet<BytesRef>();

            int num = AtLeast(200);
            for (int i = 0; i < num; i++)
            {
                string s = TestUtil.RandomUnicodeString(Random());
                field.StringValue = s;
                Terms.Add(new BytesRef(s));
                writer.AddDocument(doc);
            }

            TermsAutomaton = BasicAutomata.MakeStringUnion(Terms);

            Reader = writer.Reader;
            Searcher = NewSearcher(Reader);
            writer.Dispose();
        }
        public void BeforeClass()
        {
            Dir = NewDirectory();
            Sdir1 = NewDirectory();
            Sdir2 = NewDirectory();
            RandomIndexWriter writer = new RandomIndexWriter(Random(), Dir, new MockAnalyzer(Random()), Similarity, TimeZone);
            RandomIndexWriter swriter1 = new RandomIndexWriter(Random(), Sdir1, new MockAnalyzer(Random()), Similarity, TimeZone);
            RandomIndexWriter swriter2 = new RandomIndexWriter(Random(), Sdir2, new MockAnalyzer(Random()), Similarity, TimeZone);

            for (int i = 0; i < 10; i++)
            {
                Document doc = new Document();
                doc.Add(NewStringField("data", Convert.ToString(i), Field.Store.NO));
                writer.AddDocument(doc);
                ((i % 2 == 0) ? swriter1 : swriter2).AddDocument(doc);
            }
            writer.ForceMerge(1);
            swriter1.ForceMerge(1);
            swriter2.ForceMerge(1);
            writer.Dispose();
            swriter1.Dispose();
            swriter2.Dispose();

            Reader = DirectoryReader.Open(Dir);
            Searcher = NewSearcher(Reader);

            MultiReader = new MultiReader(new IndexReader[] { DirectoryReader.Open(Sdir1), DirectoryReader.Open(Sdir2) }, true);
            MultiSearcher = NewSearcher(MultiReader);

            MultiReaderDupls = new MultiReader(new IndexReader[] { DirectoryReader.Open(Sdir1), DirectoryReader.Open(Dir) }, true);
            MultiSearcherDupls = NewSearcher(MultiReaderDupls);
        }
Example #14
0
        public override void SetUp()
        {
            base.SetUp();
            Dir = NewDirectory();
            RandomIndexWriter writer = new RandomIndexWriter(Random(), Dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(TestUtil.NextInt(Random(), 50, 1000)));

            Document doc = new Document();
            FieldType customType = new FieldType(TextField.TYPE_STORED);
            customType.OmitNorms = true;
            Field field = NewField("field", "", customType);
            doc.Add(field);

            NumberFormatInfo df = new NumberFormatInfo();
            df.NumberDecimalDigits = 0;

            //NumberFormat df = new DecimalFormat("000", new DecimalFormatSymbols(Locale.ROOT));
            for (int i = 0; i < 1000; i++)
            {
                field.StringValue = i.ToString(df);
                writer.AddDocument(doc);
            }

            Reader = writer.Reader;
            writer.Dispose();
            Searcher = NewSearcher(Reader);
        }
        /// <summary>
        /// Save a single segment's info. </summary>
        public override void Write(Directory dir, SegmentInfo si, FieldInfos fis, IOContext ioContext)
        {
            string fileName = IndexFileNames.SegmentFileName(si.Name, "", Lucene40SegmentInfoFormat.SI_EXTENSION);
            si.AddFile(fileName);

            IndexOutput output = dir.CreateOutput(fileName, ioContext);

            bool success = false;
            try
            {
                CodecUtil.WriteHeader(output, Lucene40SegmentInfoFormat.CODEC_NAME, Lucene40SegmentInfoFormat.VERSION_CURRENT);
                // Write the Lucene version that created this segment, since 3.1
                output.WriteString(si.Version);
                output.WriteInt(si.DocCount);

                output.WriteByte((sbyte)(si.UseCompoundFile ? SegmentInfo.YES : SegmentInfo.NO));
                output.WriteStringStringMap(si.Diagnostics);
                output.WriteStringStringMap(CollectionsHelper.EmptyMap<string, string>());
                output.WriteStringSet(si.Files);

                success = true;
            }
            finally
            {
                if (!success)
                {
                    IOUtils.CloseWhileHandlingException(output);
                    si.Dir.DeleteFile(fileName);
                }
                else
                {
                    output.Dispose();
                }
            }
        }
        public VariableGapTermsIndexReader(Directory dir, FieldInfos fieldInfos, String segment, int indexDivisor,
            String segmentSuffix, IOContext context)
        {
            _input =
                dir.OpenInput(
                    IndexFileNames.SegmentFileName(segment, segmentSuffix,
                        VariableGapTermsIndexWriter.TERMS_INDEX_EXTENSION), new IOContext(context, true));
            var success = false;

            Debug.Assert(indexDivisor == -1 || indexDivisor > 0);

            try
            {

                _version = ReadHeader(_input);
                _indexDivisor = indexDivisor;

                if (_version >= VariableGapTermsIndexWriter.VERSION_CHECKSUM)
                    CodecUtil.ChecksumEntireFile(_input);
                
                SeekDir(_input, _dirOffset);

                // Read directory
                var numFields = _input.ReadVInt();
                if (numFields < 0)
                {
                    throw new CorruptIndexException("invalid numFields: " + numFields + " (resource=" + _input + ")");
                }

                for (var i = 0; i < numFields; i++)
                {
                    var field = _input.ReadVInt();
                    var indexStart = _input.ReadVLong();
                    var fieldInfo = fieldInfos.FieldInfo(field);
                    
                    try
                    {
                        _fields.Add(fieldInfo, new FieldIndexData(indexStart, this));
                    }
                    catch (ArgumentException)
                    {
                        throw new CorruptIndexException(String.Format("Duplicate Field: {0}, Resource: {1}",
                            fieldInfo.Name, _input));
                    }
                }
                success = true;
            }
            finally
            {
                if (indexDivisor > 0)
                {
                    _input.Dispose();
                    _input = null;
                    if (success)
                    {
                        _indexLoaded = true;
                    }
                }
            }
        }
Example #17
0
 public void getParent()
 {
     Directory racine = new Directory("racine", null, 7);
     Directory test = new Directory("test", racine, 7);
     Assert.AreEqual(racine, test.getParent());
     // la commande parent ne marche pas dans le programme, c'est pour ça que le test unitaire ne marche pas non plus
 }
        public MapIconUserControl(Directory directory)
        {
            this.InitializeComponent();
            (this.Content as FrameworkElement).DataContext = this;

            Directory = directory;
        }
Example #19
0
        public virtual void CreateRandomTerms(int nDocs, int nTerms, double power, Directory dir)
        {
            int[] freq = new int[nTerms];
            Terms = new Term[nTerms];
            for (int i = 0; i < nTerms; i++)
            {
                int f = (nTerms + 1) - i; // make first terms less frequent
                freq[i] = (int)Math.Ceiling(Math.Pow(f, power));
                Terms[i] = new Term("f", char.ToString((char)('A' + i)));
            }

            IndexWriter iw = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetOpenMode(OpenMode.CREATE));
            for (int i = 0; i < nDocs; i++)
            {
                Document d = new Document();
                for (int j = 0; j < nTerms; j++)
                {
                    if (Random().Next(freq[j]) == 0)
                    {
                        d.Add(NewStringField("f", Terms[j].Text(), Field.Store.NO));
                        //System.out.println(d);
                    }
                }
                iw.AddDocument(d);
            }
            iw.ForceMerge(1);
            iw.Dispose();
        }
Example #20
0
		public File(Filesystem parent, Directory parentDir, string name, int id)
		{
			this.parentP = parent;
			this.parentDirP = parentDir;
			this.nameP = name;
			this.idP = id;
		}
Example #21
0
        public override void SetUp()
        {
            base.SetUp();
            Dir = NewDirectory();
            RandomIndexWriter writer = new RandomIndexWriter(Random(), Dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())).SetMaxBufferedDocs(TestUtil.NextInt(Random(), 50, 1000)));

            Document doc = new Document();
            Field field = NewStringField("field", "", Field.Store.NO);
            doc.Add(field);

            NumberFormatInfo df = new NumberFormatInfo();
            df.NumberDecimalDigits = 0;

            //NumberFormat df = new DecimalFormat("000", new DecimalFormatSymbols(Locale.ROOT));
            for (int i = 0; i < 1000; i++)
            {
                field.StringValue = i.ToString(df);
                writer.AddDocument(doc);
            }

            Reader = writer.Reader;
            Searcher = NewSearcher(Reader);
            writer.Dispose();
            if (VERBOSE)
            {
                Console.WriteLine("TEST: setUp searcher=" + Searcher);
            }
        }
 internal TestIndex(Random random, int minR, int maxR, bool allowNegativeRandomInts)
 {
     this.MinR = minR;
     this.MaxR = maxR;
     this.AllowNegativeRandomInts = allowNegativeRandomInts;
     Index = NewDirectory(random);
 }
        public override void SetUp()
        {
            base.SetUp();
            Document doc;
            Rd1 = NewDirectory();
            IndexWriter iw1 = new IndexWriter(Rd1, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));

            doc = new Document();
            doc.Add(NewTextField("field1", "the quick brown fox jumps", Field.Store.YES));
            doc.Add(NewTextField("field2", "the quick brown fox jumps", Field.Store.YES));
            iw1.AddDocument(doc);

            iw1.Dispose();
            Rd2 = NewDirectory();
            IndexWriter iw2 = new IndexWriter(Rd2, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));

            doc = new Document();
            doc.Add(NewTextField("field1", "the fox jumps over the lazy dog", Field.Store.YES));
            doc.Add(NewTextField("field3", "the fox jumps over the lazy dog", Field.Store.YES));
            iw2.AddDocument(doc);

            iw2.Dispose();

            this.Ir1 = SlowCompositeReaderWrapper.Wrap(DirectoryReader.Open(Rd1));
            this.Ir2 = SlowCompositeReaderWrapper.Wrap(DirectoryReader.Open(Rd2));
        }
Example #24
0
        public static void BeforeClass()
        {
            Dir = NewDirectory();
            RandomIndexWriter iw = new RandomIndexWriter(Random(), Dir);
            int numDocs = AtLeast(300);
            for (int i = 0; i < numDocs; i++)
            {
                Document doc = new Document();

                AddSome(doc, AlwaysTerms);

                if (Random().Next(100) < 90)
                {
                    AddSome(doc, CommonTerms);
                }
                if (Random().Next(100) < 50)
                {
                    AddSome(doc, MediumTerms);
                }
                if (Random().Next(100) < 10)
                {
                    AddSome(doc, RareTerms);
                }
                iw.AddDocument(doc);
            }
            iw.ForceMerge(1);
            iw.Dispose();
            r = DirectoryReader.Open(Dir);
            atomicReader = GetOnlySegmentReader(r);
            Searcher = new IndexSearcher(atomicReader);
            Searcher.Similarity = new DefaultSimilarityAnonymousInnerClassHelper();
        }
        public PreFlexRWStoredFieldsWriter(Directory directory, string segment, IOContext context)
        {
            Debug.Assert(directory != null);
            this.Directory = directory;
            this.Segment = segment;

            bool success = false;
            try
            {
                FieldsStream = directory.CreateOutput(IndexFileNames.SegmentFileName(segment, "", Lucene3xStoredFieldsReader.FIELDS_EXTENSION), context);
                IndexStream = directory.CreateOutput(IndexFileNames.SegmentFileName(segment, "", Lucene3xStoredFieldsReader.FIELDS_INDEX_EXTENSION), context);

                FieldsStream.WriteInt(Lucene3xStoredFieldsReader.FORMAT_CURRENT);
                IndexStream.WriteInt(Lucene3xStoredFieldsReader.FORMAT_CURRENT);

                success = true;
            }
            finally
            {
                if (!success)
                {
                    Abort();
                }
            }
        }
Example #26
0
  public static int Main(string[] args)
    {
    string directory = args[0];
    Tag t = new Tag(0x8,0x80);

    Directory d = new Directory();
    uint nfiles = d.Load( directory );
    if(nfiles == 0) return 1;
    //System.Console.WriteLine( "Files:\n" + d.toString() );

    // Use a StrictScanner, need to use a reference to pass the C++ pointer to
    // MyWatcher implementation
    SmartPtrStrictScan sscan = StrictScanner.New();
    StrictScanner s = sscan.__ref__();
    MyWatcher watcher = new MyWatcher(s);

    s.AddTag( t );
    bool b = s.Scan( d.GetFilenames() );
    if(!b) return 1;

    for(int i = 0; i < (int)nfiles; ++i)
      {
      if( !s.IsKey( d.GetFilenames()[i] ) )
        {
        System.Console.WriteLine( "File is not DICOM or could not be read: " + d.GetFilenames()[i] );
        }
      }

    System.Console.WriteLine( "Scan:\n" + s.toString() );

    System.Console.WriteLine( "success" );
    return 0;
    }
Example #27
0
		/// <summary>Creates engine based on provided <paramref name="directoryInfo"/>.</summary>
		public static Engine CreateStandard(DirectoryInfo directoryInfo)
		{
			var directory = new Directory(directoryInfo);
			var documentAssembler = new DesignDocumentAssembler(directory);
			var designDocumentExtractor = new DesignDocumentExtractor();
			return new Engine(designDocumentExtractor, documentAssembler);
		}
Example #28
0
 public void ls()
 {
     Directory racine = new Directory("racine", null, 7);
     Directory test = new Directory("test", racine, 7);
     racine.listeFile.Add(test);
     Assert.AreEqual(racine.listeFile, racine.ls());
 }
Example #29
0
 public File(Directory directory, string filePath)
 {
     FilePath = filePath;
     Directory = directory;
     FileExtension = Path.GetExtension(FilePath);
     FileName = FilePath.Split(Constants.PathSeparator).Last();
 }
        // ReSharper disable once SuggestBaseTypeForParameter
        public PendingDirectory(InstallationDirectory installationDirectory, SystemClock clock)
        {
            _pendingLocation = installationDirectory.GetChildDirectory(LocationExtensions.Pending);
            _pendingLocation.EnsureExists();

            _clock = clock;
        }
 private bool DirectoryExists(string path)
 {
     return(Directory.Exists(GetExactPath(path)));
 }
Example #32
0
        public override TaskOrResult<EffectBytecodeCompilerResult> Compile(ShaderMixinSource mixinTree, EffectCompilerParameters effectParameters, CompilerParameters compilerParameters)
        {
            var log = new LoggerResult();

            // Load D3D compiler dll
            // Note: No lock, it's probably fine if it gets called from multiple threads at the same time.
            if (Platform.IsWindowsDesktop && !d3dCompilerLoaded)
            {
                NativeLibrary.PreloadLibrary("d3dcompiler_47.dll", typeof(EffectCompiler));
                d3dCompilerLoaded = true;
            }

            var shaderMixinSource = mixinTree;
            var fullEffectName = mixinTree.Name;

            // Make a copy of shaderMixinSource. Use deep clone since shaderMixinSource can be altered during compilation (e.g. macros)
            var shaderMixinSourceCopy = new ShaderMixinSource();
            shaderMixinSourceCopy.DeepCloneFrom(shaderMixinSource);
            shaderMixinSource = shaderMixinSourceCopy;

            // Generate platform-specific macros
            switch (effectParameters.Platform)
            {
                case GraphicsPlatform.Direct3D11:
                    shaderMixinSource.AddMacro("XENKO_GRAPHICS_API_DIRECT3D", 1);
                    shaderMixinSource.AddMacro("XENKO_GRAPHICS_API_DIRECT3D11", 1);
                    break;
                case GraphicsPlatform.Direct3D12:
                    shaderMixinSource.AddMacro("XENKO_GRAPHICS_API_DIRECT3D", 1);
                    shaderMixinSource.AddMacro("XENKO_GRAPHICS_API_DIRECT3D12", 1);
                    break;
                case GraphicsPlatform.OpenGL:
                    shaderMixinSource.AddMacro("XENKO_GRAPHICS_API_OPENGL", 1);
                    shaderMixinSource.AddMacro("XENKO_GRAPHICS_API_OPENGLCORE", 1);
                    break;
                case GraphicsPlatform.OpenGLES:
                    shaderMixinSource.AddMacro("XENKO_GRAPHICS_API_OPENGL", 1);
                    shaderMixinSource.AddMacro("XENKO_GRAPHICS_API_OPENGLES", 1);
                    break;
                case GraphicsPlatform.Vulkan:
                    shaderMixinSource.AddMacro("XENKO_GRAPHICS_API_VULKAN", 1);
                    break;
                default:
                    throw new NotSupportedException();
            }

            // Generate profile-specific macros
            shaderMixinSource.AddMacro("XENKO_GRAPHICS_PROFILE", (int)effectParameters.Profile);
            shaderMixinSource.AddMacro("GRAPHICS_PROFILE_LEVEL_9_1", (int)GraphicsProfile.Level_9_1);
            shaderMixinSource.AddMacro("GRAPHICS_PROFILE_LEVEL_9_2", (int)GraphicsProfile.Level_9_2);
            shaderMixinSource.AddMacro("GRAPHICS_PROFILE_LEVEL_9_3", (int)GraphicsProfile.Level_9_3);
            shaderMixinSource.AddMacro("GRAPHICS_PROFILE_LEVEL_10_0", (int)GraphicsProfile.Level_10_0);
            shaderMixinSource.AddMacro("GRAPHICS_PROFILE_LEVEL_10_1", (int)GraphicsProfile.Level_10_1);
            shaderMixinSource.AddMacro("GRAPHICS_PROFILE_LEVEL_11_0", (int)GraphicsProfile.Level_11_0);
            shaderMixinSource.AddMacro("GRAPHICS_PROFILE_LEVEL_11_1", (int)GraphicsProfile.Level_11_1);
            shaderMixinSource.AddMacro("GRAPHICS_PROFILE_LEVEL_11_2", (int)GraphicsProfile.Level_11_2);

            // In .xksl, class has been renamed to shader to avoid ambiguities with HLSL
            shaderMixinSource.AddMacro("class", "shader");

            var parsingResult = GetMixinParser().Parse(shaderMixinSource, shaderMixinSource.Macros.ToArray());

            // Copy log from parser results to output
            CopyLogs(parsingResult, log);

            // Return directly if there are any errors
            if (parsingResult.HasErrors)
            {
                return new EffectBytecodeCompilerResult(null, log);
            }

            // Convert the AST to HLSL
            var writer = new Xenko.Core.Shaders.Writer.Hlsl.HlslWriter
            {
                EnablePreprocessorLine = false, // Allow to output links to original pdxsl via #line pragmas
            };
            writer.Visit(parsingResult.Shader);
            var shaderSourceText = writer.Text;

            if (string.IsNullOrEmpty(shaderSourceText))
            {
                log.Error($"No code generated for effect [{fullEffectName}]");
                return new EffectBytecodeCompilerResult(null, log);
            }

            // -------------------------------------------------------
            // Save shader log
            // TODO: TEMP code to allow debugging generated shaders on Windows Desktop
#if XENKO_PLATFORM_WINDOWS_DESKTOP
            var shaderId = ObjectId.FromBytes(Encoding.UTF8.GetBytes(shaderSourceText));

            var logDir = Path.Combine(PlatformFolders.ApplicationBinaryDirectory, "log");
            if (!Directory.Exists(logDir))
            {
                Directory.CreateDirectory(logDir);
            }
            var shaderSourceFilename = Path.Combine(logDir, "shader_" + fullEffectName.Replace('.', '_') + "_" + shaderId + ".hlsl");
            lock (WriterLock) // protect write in case the same shader is created twice
            {
                // Write shader before generating to make sure that we are having a trace before compiling it (compiler may crash...etc.)
                if (!File.Exists(shaderSourceFilename))
                {
                    File.WriteAllText(shaderSourceFilename, shaderSourceText);
                }
            }
#else
            string shaderSourceFilename = null;
#endif
            // -------------------------------------------------------

            var bytecode = new EffectBytecode { Reflection = parsingResult.Reflection, HashSources = parsingResult.HashSources };

            // Select the correct backend compiler
            IShaderCompiler compiler;
            switch (effectParameters.Platform)
            {
#if XENKO_PLATFORM_WINDOWS
                case GraphicsPlatform.Direct3D11:
                case GraphicsPlatform.Direct3D12:
                    compiler = new Direct3D.ShaderCompiler();
                    break;
#endif
                case GraphicsPlatform.OpenGL:
                case GraphicsPlatform.OpenGLES:
                case GraphicsPlatform.Vulkan:
                    // get the number of render target outputs
                    var rtOutputs = 0;
                    var psOutput = parsingResult.Shader.Declarations.OfType<StructType>().FirstOrDefault(x => x.Name.Text == "PS_OUTPUT");
                    if (psOutput != null)
                    {
                        foreach (var rto in psOutput.Fields)
                        {
                            var sem = rto.Qualifiers.OfType<Semantic>().FirstOrDefault();
                            if (sem != null)
                            {
                                // special case SV_Target
                                if (rtOutputs == 0 && sem.Name.Text == "SV_Target")
                                {
                                    rtOutputs = 1;
                                    break;
                                }
                                for (var i = rtOutputs; i < 8; ++i)
                                {
                                    if (sem.Name.Text == ("SV_Target" + i))
                                    {
                                        rtOutputs = i + 1;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    compiler = new OpenGL.ShaderCompiler(rtOutputs);
                    break;
                default:
                    throw new NotSupportedException();
            }

            var shaderStageBytecodes = new List<ShaderBytecode>();

#if XENKO_PLATFORM_WINDOWS_DESKTOP
            var stageStringBuilder = new StringBuilder();
#endif
            // if the shader (non-compute) does not have a pixel shader, we should add it for OpenGL and OpenGL ES.
            if ((effectParameters.Platform == GraphicsPlatform.OpenGL || effectParameters.Platform == GraphicsPlatform.OpenGLES) && !parsingResult.EntryPoints.ContainsKey(ShaderStage.Pixel) && !parsingResult.EntryPoints.ContainsKey(ShaderStage.Compute))
            {
                parsingResult.EntryPoints.Add(ShaderStage.Pixel, null);
            }

            foreach (var stageBinding in parsingResult.EntryPoints)
            {
                // Compile
                // TODO: We could compile stages in different threads to improve compiler throughput?
                var result = compiler.Compile(shaderSourceText, stageBinding.Value, stageBinding.Key, effectParameters, bytecode.Reflection, shaderSourceFilename);
                result.CopyTo(log);

                if (result.HasErrors)
                {
                    continue;
                }

                // -------------------------------------------------------
                // Append bytecode id to shader log
#if XENKO_PLATFORM_WINDOWS_DESKTOP
                stageStringBuilder.AppendLine("@G    {0} => {1}".ToFormat(stageBinding.Key, result.Bytecode.Id));
                if (result.DisassembleText != null)
                {
                    stageStringBuilder.Append(result.DisassembleText);
                }
#endif
                // -------------------------------------------------------

                shaderStageBytecodes.Add(result.Bytecode);

                // When this is a compute shader, there is no need to scan other stages
                if (stageBinding.Key == ShaderStage.Compute)
                    break;
            }

            // Remove unused reflection data, as it is entirely resolved at compile time.
            CleanupReflection(bytecode.Reflection);
            bytecode.Stages = shaderStageBytecodes.ToArray();

#if XENKO_PLATFORM_WINDOWS_DESKTOP
            int shaderSourceLineOffset = 0;
            int shaderSourceCharacterOffset = 0;
            string outputShaderLog;
            lock (WriterLock) // protect write in case the same shader is created twice
            {
                var builder = new StringBuilder();
                builder.AppendLine("/**************************");
                builder.AppendLine("***** Compiler Parameters *****");
                builder.AppendLine("***************************");
                builder.Append("@P EffectName: ");
                builder.AppendLine(fullEffectName ?? "");
                builder.Append(compilerParameters?.ToStringPermutationsDetailed());
                builder.AppendLine("***************************");

                if (bytecode.Reflection.ConstantBuffers.Count > 0)
                {
                    builder.AppendLine("****  ConstantBuffers  ****");
                    builder.AppendLine("***************************");
                    foreach (var cBuffer in bytecode.Reflection.ConstantBuffers)
                    {
                        builder.AppendFormat("cbuffer {0} [Size: {1}]", cBuffer.Name, cBuffer.Size).AppendLine();
                        foreach (var parameter in cBuffer.Members)
                        {
                            builder.AppendFormat("@C    {0} => {1}", parameter.RawName, parameter.KeyInfo.KeyName).AppendLine();
                        }
                    }
                    builder.AppendLine("***************************");
                }

                if (bytecode.Reflection.ResourceBindings.Count > 0)
                {
                    builder.AppendLine("******  Resources    ******");
                    builder.AppendLine("***************************");
                    foreach (var resource in bytecode.Reflection.ResourceBindings)
                    {
                        builder.AppendFormat("@R    {0} => {1} [Stage: {2}, Slot: ({3}-{4})]", resource.RawName, resource.KeyInfo.KeyName, resource.Stage, resource.SlotStart, resource.SlotStart + resource.SlotCount - 1).AppendLine();
                    }
                    builder.AppendLine("***************************");
                }

                if (bytecode.HashSources.Count > 0)
                {
                    builder.AppendLine("*****     Sources     *****");
                    builder.AppendLine("***************************");
                    foreach (var hashSource in bytecode.HashSources)
                    {
                        builder.AppendFormat("@S    {0} => {1}", hashSource.Key, hashSource.Value).AppendLine();
                    }
                    builder.AppendLine("***************************");
                }

                if (bytecode.Stages.Length > 0)
                {
                    builder.AppendLine("*****     Stages      *****");
                    builder.AppendLine("***************************");
                    builder.Append(stageStringBuilder);
                    builder.AppendLine("***************************");
                }
                builder.AppendLine("*************************/");

                shaderSourceCharacterOffset = builder.Length;

                // Re-append the shader with all informations
                builder.Append(shaderSourceText);

                outputShaderLog = builder.ToString();
                File.WriteAllText(shaderSourceFilename, outputShaderLog);
            }

            // Count lines till source start
            for (int i = 0; i < shaderSourceCharacterOffset-1;)
            {
                if (outputShaderLog[i] == '\r' && outputShaderLog[i + 1] == '\n')
                {
                    shaderSourceLineOffset++;
                    i += 2;
                }
                else
                    i++;
            }

            // Rewrite shader log
            Regex shaderLogReplace = new Regex(@"\.hlsl\((\d+),[0-9\-]+\):");
            foreach (var msg in log.Messages)
            {
                var match = shaderLogReplace.Match(msg.Text);
                if (match.Success)
                {
                    int line = int.Parse(match.Groups[1].Value);
                    line += shaderSourceLineOffset;

                    msg.Text = msg.Text.Remove(match.Groups[1].Index, match.Groups[1].Length)
                        .Insert(match.Groups[1].Index, line.ToString());
                }
            }
#endif

            return new EffectBytecodeCompilerResult(bytecode, log);
        }
Example #33
0
        public Publicar(Form inicio, Panel top, string user)
        {
            string url = Directory.GetCurrentDirectory();

            newURL = "";
            for (int i = 0; i < url.Length - 9; i++)
            {
                newURL += url[i];
            }

            panelPrincipal.SetBounds(42, 62, 668, 418);
            inicio.Controls.Add(panelPrincipal);
            panelPrincipal.BringToFront();
            panelPrincipal.BorderStyle = BorderStyle.FixedSingle;

            salir.Text   = "X";
            salir.Cursor = Cursors.Hand;
            panelPrincipal.Controls.Add(salir);
            salir.SetBounds(panelPrincipal.Width - 50, 8, 40, 30);
            salir.FlatStyle = FlatStyle.Flat;
            salir.FlatAppearance.BorderSize = 0;
            salir.Click += (s, ev) => { inicio.Controls.Remove(panelPrincipal); inicio.ActiveControl = top; };

            titulo.Text = "Titulo: ";
            panel.Controls.Add(titulo);
            titulo.SetBounds(20, 20, titulo.Text.Length * 5 + 2, 14);

            panel.Controls.Add(Ttitulo);
            Ttitulo.SetBounds(titulo.Location.X + 44, titulo.Location.Y, 180, 14);
            Ttitulo.BackColor   = Color.WhiteSmoke;
            Ttitulo.BorderStyle = BorderStyle.None;
            Ttitulo.MaxLength   = 30;

            descripcion.Text = "Descripción: ";
            panel.Controls.Add(descripcion);
            descripcion.SetBounds(20, 50, descripcion.Text.Length * 6, 14);

            panel.Controls.Add(Tdescripcion);
            Tdescripcion.SetBounds(descripcion.Location.X + 4, descripcion.Location.Y + 20, 220, 50);
            Tdescripcion.BackColor   = Color.WhiteSmoke;
            Tdescripcion.Multiline   = true;
            Tdescripcion.BorderStyle = BorderStyle.None;
            Tdescripcion.MaxLength   = 100;


            panel.SetBounds(panelPrincipal.Width / 2 + 40, 80, panelPrincipal.Width / 2 - 60, panelPrincipal.Height / 2);

            panelPrincipal.Controls.Add(panel);
            panel.BringToFront();


            var   label    = new Label();
            var   filePath = string.Empty;
            Image image    = Image.FromFile(newURL + "\\Imagenes\\FotoPerfil.jpg");

            panelPrincipal.Controls.Add(select);
            panelPrincipal.Controls.Add(imagenPrincipal);
            imagenPrincipal.SetBounds(0, 0, panelPrincipal.Width / 2 + 20, panelPrincipal.Height);
            imagenPrincipal.BackColor = Color.Black;
            imagenPrincipal.SizeMode  = PictureBoxSizeMode.Zoom;

            select.Text = "+";
            select.Font = new Font("Calibri", 8);
            select.SetBounds(0, 0, 20, 20);
            select.FlatStyle = FlatStyle.Flat;
            select.Click    += (s, ev) => {
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.Filter           = " Image files|*.bmp;*.jpg;*.png;";
                openFileDialog.RestoreDirectory = true;
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    panelPrincipal.Controls.Remove(label);
                    filePath = openFileDialog.FileName;
                    image    = Image.FromFile(filePath);
                    imagenPrincipal.Image = image;
                }
            };

            add.Text   = "Publicar";
            add.Cursor = Cursors.Hand;
            panelPrincipal.Controls.Add(add);
            add.BackColor = Color.DeepSkyBlue;
            add.ForeColor = Color.White;
            add.SetBounds(panelPrincipal.Width - 110, panelPrincipal.Height - 56, 80, 30);
            add.FlatStyle = FlatStyle.Flat;
            add.FlatAppearance.BorderSize = 0;
            add.Click += (s, ev) => {
                var data     = filePath.Split('\\');
                var urlImage = "Imagenes\\" + data[data.Length - 1];
                if (urlImage.Length > 10)
                {
                    image.Save(newURL + urlImage);
                    proxy.CrearPost(user, Ttitulo.Text, Tdescripcion.Text, urlImage);
                    inicio.Controls.Remove(panelPrincipal);
                    inicio.ActiveControl = top;
                }
            };
        }
Example #34
0
        /// <summary>
        /// Loads files and folders into the local datagridview
        /// </summary>
        /// <param name="directoryPath"> </param>
        public void LoadLocalDirectory(string directoryPath)
        {
            try
            {
                GridLocalFiles.DataSource = null;

                DataTable localFiles = DataExtensions.CreateDataTable(
                    new List <DataColumn>
                {
                    new() { Caption = "Type", ColumnName = "Type", DataType = typeof(string) },
                    new() { Caption = "Image", ColumnName = "Image", DataType = typeof(Image) },
                    new() { Caption = "Name", ColumnName = "Name", DataType = typeof(string) },
                    new() { Caption = "Size", ColumnName = "Size", DataType = typeof(string) },
                    new() { Caption = "Last Modified", ColumnName = "Last Modified", DataType = typeof(string) }
                });

                DirectoryPathLocal    = directoryPath.Replace(@"\\", @"\");
                TextBoxLocalPath.Text = DirectoryPathLocal;

                SetLocalStatus($"Fetching directory listing of '{DirectoryPathLocal}'...");

                ComboBoxLocalDrives.SelectedIndexChanged -= ComboBoxLocalDrives_SelectedIndexChanged;
                ComboBoxLocalDrives.SelectedItem          = DirectoryPathLocal.Substring(0, 2);
                ComboBoxLocalDrives.SelectedIndexChanged += ComboBoxLocalDrives_SelectedIndexChanged;

                bool isParentRoot = LocalDrives.Any(x => x.Name.Equals(DirectoryPathLocal.Replace(@"\\", @"\")));

                if (!isParentRoot)
                {
                    localFiles.Rows.Add("folder", ImageFolder, "..", "<DIRECTORY>", Directory.GetLastWriteTime(DirectoryPathLocal));
                }

                int  folders    = 0;
                int  files      = 0;
                long totalBytes = 0;

                foreach (string directoryItem in Directory.GetDirectories(DirectoryPathLocal))
                {
                    localFiles.Rows.Add("folder", ImageFolder, Path.GetFileName(directoryItem), "<DIRECTORY>", Directory.GetLastWriteTime(directoryItem));

                    folders++;
                }

                foreach (string fileItem in Directory.GetFiles(DirectoryPathLocal))
                {
                    long fileBytes = new FileInfo(fileItem).Length;

                    localFiles.Rows.Add("file", ImageFile, Path.GetFileName(fileItem), Settings.ShowFileSizeInBytes ? fileBytes + " bytes" : fileBytes.FormatBytes(), File.GetLastWriteTime(fileItem));

                    files++;
                    totalBytes += fileBytes;
                }

                string statusFiles      = files > 0 ? $"{files} {(files <= 1 ? "file" : "files")} {(files > 0 && folders > 0 ? "and " : "")}" : "" + $"{(folders < 1 ? "." : "")}";
                string statusFolders    = folders > 0 ? $"{folders} {(folders <= 1 ? "directory" : "directories")}. " : "";
                string statusTotalBytes = files > 0 ? $"Total size: {(Settings.ShowFileSizeInBytes ? totalBytes + " bytes" : totalBytes.FormatBytes())}" : "";

                if (files < 1 && folders < 1)
                {
                    SetLocalStatus("Empty directory.");
                }
                else
                {
                    SetLocalStatus($"{statusFiles}{statusFolders}{statusTotalBytes}");
                }

                GridLocalFiles.DataSource = localFiles;

                GridViewLocalFiles.Columns[0].Visible = false;
                GridViewLocalFiles.Columns[1].Caption = " ";
                GridViewLocalFiles.Columns[1].Width   = 10;
                GridViewLocalFiles.Columns[2].Width   = 300;
                GridViewLocalFiles.Columns[3].Width   = 100;
                GridViewLocalFiles.Columns[4].Width   = 100;

                SetLocalStatus("Successfully fetched directory listing.");
            }
    private bool HandleNonMainCommand(GitVersionOptions gitVersionOptions, out int exitCode)
    {
        if (gitVersionOptions.IsVersion)
        {
            var assembly = Assembly.GetExecutingAssembly();
            this.versionWriter.Write(assembly);
            exitCode = 0;
            return(true);
        }

        if (gitVersionOptions.IsHelp)
        {
            this.helpWriter.Write();
            exitCode = 0;
            return(true);
        }

        if (gitVersionOptions.Diag)
        {
            gitVersionOptions.Settings.NoCache = true;
            gitVersionOptions.Output.Add(OutputType.BuildServer);
        }

        ConfigureLogging(gitVersionOptions, this.log);

        var workingDirectory = gitVersionOptions.WorkingDirectory;

        if (gitVersionOptions.Diag)
        {
            this.log.Info("Dumping commit graph: ");
            GitExtensions.DumpGraph(workingDirectory, mess => this.log.Info(mess), 100);
        }

        if (!Directory.Exists(workingDirectory))
        {
            this.log.Warning($"The working directory '{workingDirectory}' does not exist.");
        }
        else
        {
            this.log.Info("Working directory: " + workingDirectory);
        }

        this.configFileLocator.Verify(gitVersionOptions, this.repositoryInfo);

        if (gitVersionOptions.Init)
        {
            this.configProvider.Init(workingDirectory);
            exitCode = 0;
            return(true);
        }

        if (gitVersionOptions.ConfigInfo.ShowConfig)
        {
            var config = this.configProvider.Provide(workingDirectory);
            this.console.WriteLine(config.ToString());
            exitCode = 0;
            return(true);
        }

        exitCode = 0;
        return(false);
    }
        public void Firstnewsletter(NewsLetterModel Model)
        {
            Model.FirstContent = FirstContent.Text;
            Model.SecondContent = SecondContent.Text;
            Model.ThirldContent = ThirdContent.Text;

            string SelectedIds = GetHiddenValue();

            if (First_newsletter_Imgfile.PostedFile != null && First_newsletter_Imgfile.PostedFile.FileName != "")
            {

                var fileExt = Path.GetExtension(First_newsletter_Imgfile.FileName);
                string fileName = Guid.NewGuid() + fileExt;
                var subPath = Server.MapPath("~/uploadfiles");

                //Check SubPath Exist or Not
                if (!Directory.Exists(subPath))
                {
                    Directory.CreateDirectory(subPath);
                }
                //End : Check SubPath Exist or Not

                var path = Path.Combine(subPath, fileName);
                First_newsletter_Imgfile.SaveAs(path);
                var URL = ConfigurationManager.AppSettings["LiveURL"].ToString();
                Model.PropertyPhoto = URL + "/uploadfiles/" + fileName;
            }


            if (First_newsletter_Logo.PostedFile != null && First_newsletter_Logo.PostedFile.FileName != "")
            {

                //Save the photo in Folder
                var fileExt = Path.GetExtension(First_newsletter_Logo.FileName);
                string fileName = Guid.NewGuid() + fileExt;
                var subPath = Server.MapPath("~/uploadfiles");

                //Check SubPath Exist or Not
                if (!Directory.Exists(subPath))
                {
                    Directory.CreateDirectory(subPath);
                }
                //End : Check SubPath Exist or Not

                var path = Path.Combine(subPath, fileName);
                First_newsletter_Logo.SaveAs(path);
                var URL = ConfigurationManager.AppSettings["LiveURL"].ToString();
                Model.Logopath = URL + "/uploadfiles/" + fileName;
            }
            //else
            //{
            //    Model.Logopath = "..http://pavansharma.ca//images/MyLogodd%20-%20Copy.png";
            //}
            Model.AdminPhoto = "http://pavansharma.ca//images/ajay_shah.jpg";



            if (conn.State == ConnectionState.Closed)
            {
                conn.Open();
            }

            DataTable dt = new DataTable();
            string str = "select EmailId from [AdminClient] where ID in(" + SelectedIds + ")";
            SqlDataAdapter adp = new SqlDataAdapter(str, conn);
            adp.Fill(dt);

            foreach (DataRow row in dt.Rows)
            {
                var Email = row["EmailId"].ToString();
                Model.Email = Email;
                SendNewsLetter(Model);
            }
        }
Example #37
0
        static void Main(string[] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine("Not enough arguments: inputdb2 outputcsv (optional: build)");
                return;
            }

            var filename = args[0];
            var outputcsv = args[1];

            if (!File.Exists(filename))
            {
                throw new Exception("Input DB2 file does not exist!");
            }

            if (!Directory.Exists(Path.GetDirectoryName(outputcsv)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(outputcsv));
            }

            var build = "";
            if(args.Length == 3)
            {
                build = args[2];
            }

            DB2Reader reader;

            var stream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
            using (var bin = new BinaryReader(stream))
            {
                var identifier = new string(bin.ReadChars(4));
                stream.Position = 0;
                switch (identifier)
                {
                    case "WDC3":
                        reader = new WDC3Reader(stream);
                        break;
                    case "WDC2":
                        reader = new WDC2Reader(stream);
                        break;
                    case "WDC1":
                        reader = new WDC1Reader(stream);
                        break;
                    default:
                        throw new Exception("DBC type " + identifier + " is not supported!");
                }
            }

            var defs = new Structs.DBDefinition();

            foreach (var file in Directory.GetFiles("definitions/"))
            {
                if (Path.GetFileNameWithoutExtension(file).ToLower() == Path.GetFileNameWithoutExtension(filename.ToLower()))
                {
                    defs = new DBDReader().Read(file);
                }
            }

            var writer = new StreamWriter(outputcsv);

            Structs.VersionDefinitions? versionToUse;

            if (!Utils.GetVersionDefinitionByLayoutHash(defs, reader.LayoutHash.ToString("X8"), out versionToUse))
            {
                if (!string.IsNullOrWhiteSpace(build))
                {
                    if (!Utils.GetVersionDefinitionByBuild(defs, new Build(build), out versionToUse))
                    {
                        throw new Exception("No valid definition found for this layouthash or build!");
                    }
                }
                else
                {
                    throw new Exception("No valid definition found for this layouthash and was not able to search by build!");
                }
            }

            var aName = new AssemblyName("DynamicAssemblyExample");
            var ab = AssemblyBuilder.DefineDynamicAssembly(aName, AssemblyBuilderAccess.Run);
            var mb = ab.DefineDynamicModule(aName.Name);
            var tb = mb.DefineType(Path.GetFileNameWithoutExtension(filename) + "Struct", TypeAttributes.Public);

            foreach (var field in versionToUse.Value.definitions)
            {
                var fbNumber = tb.DefineField(field.name, DBDefTypeToType(defs.columnDefinitions[field.name].type, field.size, field.isSigned, field.arrLength), FieldAttributes.Public);
                if (field.isID)
                {
                    var constructorParameters = new Type[] { };
                    var constructorInfo = typeof(IndexAttribute).GetConstructor(constructorParameters);
                    var displayNameAttributeBuilder = new CustomAttributeBuilder(constructorInfo, new object[] { });
                    fbNumber.SetCustomAttribute(displayNameAttributeBuilder);
                }
            }

            var type = tb.CreateType();
            var genericType = typeof(Storage<>).MakeGenericType(type);
            var storage = (IDictionary)Activator.CreateInstance(genericType, filename);

            if (storage.Values.Count == 0)
            {
                throw new Exception("No rows found!");
            }

            var fields = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.NonPublic | BindingFlags.Instance);

            var headerWritten = false;

            foreach (var item in storage.Values)
            {
                // Write CSV header
                if (!headerWritten)
                {
                    for (var j = 0; j < fields.Length; ++j)
                    {
                        var field = fields[j];

                        var isEndOfRecord = fields.Length - 1 == j;

                        if (field.FieldType.IsArray)
                        {
                            var a = (Array)field.GetValue(item);
                            for (var i = 0; i < a.Length; i++)
                            {
                                var isEndOfArray = a.Length - 1 == i;

                                writer.Write($"{field.Name}[{i}]");
                                if (!isEndOfArray)
                                    writer.Write(",");
                            }
                        }
                        else
                        {
                            writer.Write(field.Name);
                        }

                        if (!isEndOfRecord)
                            writer.Write(",");
                    }
                    headerWritten = true;
                    writer.WriteLine();
                }

                for (var i = 0; i < fields.Length; ++i)
                {
                    var field = fields[i];

                    var isEndOfRecord = fields.Length - 1 == i;

                    if (field.FieldType.IsArray)
                    {
                        var a = (Array)field.GetValue(item);

                        for (var j = 0; j < a.Length; j++)
                        {
                            var isEndOfArray = a.Length - 1 == j;
                            writer.Write(a.GetValue(j));

                            if (!isEndOfArray)
                                writer.Write(",");
                        }
                    }
                    else
                    {
                        var value = field.GetValue(item);
                        if (value.GetType() == typeof(string))
                            value = StringToCSVCell((string)value);

                        writer.Write(value);
                    }

                    if (!isEndOfRecord)
                        writer.Write(",");
                }

                writer.WriteLine();
            }

            writer.Dispose();
            Environment.Exit(0);
        }
Example #38
0
 public ViewSearchPathList()
 {
     this.AddViewSearchPath(AppDomain.CurrentDomain.BaseDirectory)
     .AddViewSearchPath(Directory.GetCurrentDirectory());
 }
Example #39
0
        //新規スコア作成
        public void AddNewScore()
        {
            if (textField_ == "")
            {
                EditorUtility.DisplayDialog("AddNewScore", "NewScoreNameを設定してください", "ok");
                return;
            }

            bool isSameId = scores_.Where(s => s.id_ == textField_).Any();

            if (isSameId)
            {
                EditorUtility.DisplayDialog("AddNewScore", textField_ + "は既に存在します", "ok");
                return;
            }

            if (!Directory.Exists(GetJsonPath()))
            {
                Directory.CreateDirectory(GetJsonPath());
            }

            //スコア全部ではなく、アクティブなスコアだけ保存する
            var score = GenerateFirstScore(WindowSettings.DEFAULT_SCORE_ID);

            score.id_ = textField_;

            var timelineList = new List <object>();

            foreach (var timeline in score.timelineTracks_)
            {
                //削除済み
                if (!timeline.IsExistTimeline_)
                {
                    continue;
                }

                var tackList = new List <object>();
                //tack
                foreach (var tack in timeline.tackPoints_)
                {
                    //削除済み
                    if (!tack.IsExistTack_)
                    {
                        continue;
                    }

                    var tackDict = tack.OutputDict();
                    tackList.Add(tackDict);
                }
                //timeline
                var timelineDict = timeline.OutputDict(tackList);

                timelineList.Add(timelineDict);
            }

            //score
            var scoreObject = score.OutputDict(timelineList);

            var dataStr = Json.Serialize(scoreObject);

            //var targetFilePath = Path.Combine(Application.dataPath, TimeFlowShikiSettings.TIMEFLOWSHIKI_DATA_FILEPATH);
            var targetFilePath = GetJsonPath() + "/" + score.id_ + ".json";             // "timeflowshiki.json";// + selectedFile;

            using (var sw = new StreamWriter(targetFilePath))
            {
                sw.Write(dataStr);
            }

            //更新
            RefreshDirectory();
            RefreshScoreFile();
            ReloadSavedData();
            RepaintAllWindow();
        }
Example #40
0
        public override object Execute(List <string> args)
        {
            if (args.Count != 1)
            {
                return(false);
            }

            var outDir = args[0];

            Directory.CreateDirectory(outDir);

            Console.WriteLine("Loading resource caches...");

            var count = 0;

            using (var tagsStream = Cache.OpenCacheRead())
            {
                foreach (var tag in Cache.TagCache.FindAllInGroup("bitm"))
                {
                    Console.Write("Extracting ");
                    TagPrinter.PrintTagShort(tag);

                #if !DEBUG
                    try
                    {
                #endif
                    var bitmap    = Cache.Deserialize <Bitmap>(tagsStream, tag);
                    var ddsOutDir = outDir;

                    if (bitmap.Images.Count > 1)
                    {
                        ddsOutDir = Path.Combine(outDir, tag.Index.ToString("X8"));
                        Directory.CreateDirectory(ddsOutDir);
                    }

                    for (var i = 0; i < bitmap.Images.Count; i++)
                    {
                        var outPath = Path.Combine(ddsOutDir, ((bitmap.Images.Count > 1) ? i.ToString() : tag.Index.ToString("X8")) + ".dds");
                        var ddsFile = BitmapExtractor.ExtractBitmap(Cache, bitmap, i);
                        if (ddsFile == null)
                        {
                            continue;
                        }
                        using (var outStream = File.Open(outPath, FileMode.Create, FileAccess.Write))
                            using (var writer = new EndianWriter(outStream, EndianFormat.LittleEndian))
                            {
                                ddsFile.Write(writer);
                            }
                    }
                    count++;
                #if !DEBUG
                }
                catch (Exception ex)
                {
                    Console.WriteLine("ERROR: Failed to extract bitmap: " + ex.Message);
                }
                #endif
                }
            }

            Console.WriteLine("Extracted {0} bitmaps.", count);

            return(true);
        }
        public void cleanUpStorageContainers()
        {
            ProcessDirectoryForDeletion(storageContainerPath);

            List<Item> removalList = new List<Item>();
            foreach (GameLocation loc in Game1.locations)
            {
                int i = loc.objects.Count;
                int j = 0;
                foreach (var obj in loc.objects)
                {
                    j++;
                    ModCore.ModMonitor.Log("Parsing location " + loc.name + " : object number" + j + "/" + i + " : object name: " + obj.Value.name);
                    if (obj.Value is StardewValley.Objects.Chest) {
                        int k = (obj.Value as StardewValley.Objects.Chest).items.Count;
                        int l = 0;
                    foreach (var item in (obj.Value as StardewValley.Objects.Chest).items)
                        {
                            l++;
                            ModCore.ModMonitor.Log("Parsing Chest at : " + loc.name + " X: " + obj.Key.X + " Y: " + obj.Key.Y + " : object number: " + l + "/" + k + "object name: " + item.Name);
                            if (item is CoreObject) removalList.Add(item);
                        }

                    foreach(var v in removalList)
                        {
                            (obj.Value as StardewValley.Objects.Chest).items.Remove(v);

                            SerializerDataNode t;
                            if (acceptedTypes.ContainsKey((v as CoreObject).serializationName))
                            {
                                acceptedTypes.TryGetValue((v as CoreObject).serializationName, out t);
                                string s = Path.Combine(loc.name, "Chest," + Convert.ToString((int)obj.Key.X) + "," + Convert.ToString((int)obj.Key.Y));
                                string s2 = Path.Combine(ModCore.SerializationManager.storageContainerPath, s);
                                if (!Directory.Exists(s)) Directory.CreateDirectory(s2);
                                t.serializeToContainer.Invoke(v, s2);
                            }
                        }
                        removalList.Clear();
                      }
                }
            }

            foreach (Building building in Game1.getFarm().buildings)
            {
               
                GameLocation loc =Game1.getLocationFromName(building.nameOfIndoors,true);
              ModCore.ModMonitor.Log("Cleaning up farm building: "+loc.uniqueName);
                int i = loc.objects.Count;
                int j = 0;
                foreach (var obj in loc.objects) 
                {
                    j++;
                    ModCore.ModMonitor.Log("Parsing location " + loc.name + " : object number" + j + "/" + i + " : object name: " + obj.Value.name);
                    if (obj.Value is StardewValley.Objects.Chest)
                    {
                        int k = (obj.Value as StardewValley.Objects.Chest).items.Count;
                        int l = 0;
                        foreach (var item in (obj.Value as StardewValley.Objects.Chest).items)
                        {
                            l++;
                            ModCore.ModMonitor.Log("Parsing Chest at : " + loc.name + " X: " + obj.Key.X + " Y: " + obj.Key.Y + " : object number: " + l + "/" + k + "object name: " + item.Name);
                            if (item is CoreObject) removalList.Add(item);
                        }
                        foreach(var v in removalList)
                        {
                            (obj.Value as StardewValley.Objects.Chest).items.Remove(v);

                            SerializerDataNode t;
                            if(acceptedTypes.ContainsKey((v as CoreObject).serializationName)){
                                acceptedTypes.TryGetValue((v as CoreObject).serializationName, out t);
                                string s = Path.Combine(building.nameOfIndoors, "Chest,"+Convert.ToString( (int)obj.Key.X)+","+Convert.ToString((int)obj.Key.Y));
                                string s2 = Path.Combine(ModCore.SerializationManager.storageContainerPath, s);
                                if (!Directory.Exists(s)) Directory.CreateDirectory(s2);
                                t.serializeToContainer.Invoke(v, s2);
                            }
                        }
                        removalList.Clear();
                    }
                }
            }
        }
 public virtual void CreateDirectory(string virtualPath)
 {
     Directory.CreateDirectory(MapPath(virtualPath));
 }
 public virtual void DeleteDirectory(string virtualPath)
 {
     Directory.Delete(MapPath(virtualPath));
 }
 private static bool DirectoryContains(string directory, string fileName)
 {
     return Directory.GetFiles(directory).Any(filePath => string.Equals(Path.GetFileName(filePath), fileName));
 }
        private void GetFileInfo(params string[] args)
        {
            /* Check and parse path to the file */
            var pathArg = args[0];

            string path = ExtraFunctional.ParsePath(pathArg, CurrentDirectory);


            // path can be null only if current directory is null
            if (path is null)
            {
                CurrentShownInfo = new Info(
                    "Невозможно использовать указанный путь. Укажите абсолютный путь.",
                    InfoType.Error
                    );
                return;
            }

            if (!File.Exists(path) && !Directory.Exists(path))
            {
                CurrentShownInfo = new Info(
                    "Ошибка исполнения команды: указанный файл или директория не существует.",
                    InfoType.Error
                    );
                return;
            }


            /* Get info */
            string info;

            // main information
            string name;
            string extension;
            string location;

            // size information
            long sizeBytes;

            FileAttributes attributes;


            try
            {
                if (ExtraFunctional.IsDrive(path))
                {
                    var driveInfo = new DriveInfo(path);
                    info = CreateDriveInfo(driveInfo);
                }
                else if (ExtraFunctional.IsFile(path))
                {
                    /* Collect main information */
                    name      = Path.GetFileNameWithoutExtension(path);
                    extension = Path.GetExtension(path);
                    location  = Path.GetDirectoryName(path);

                    attributes = File.GetAttributes(path);


                    /* Try to get the size of the file */
                    try
                    {
                        var      dirFilesInfo = new List <FileInfo>(new DirectoryInfo(location).GetFiles());
                        FileInfo fileInfo     = dirFilesInfo.Find(fInfo => fInfo.Name == (name + extension));

                        sizeBytes = fileInfo.Length;
                    }
                    catch (Exception e)
                    {
                        // exception will be thrown only if app has no rights to access the file or folder
                        // in that case just warn the user about it and show the size of the file as 'Неизвестно'

                        sizeBytes = -1;

                        ShowFileOperationDialog(
                            "Отказано в доступе к файлу",
                            "У приложения отсутствуют необходимые права для получения информации о размерах" +
                            $" файла {name}{extension}. Размер файла будет указан, как \"Неизвестно\".",
                            "продолжить",
                            null,
                            null
                            );
                    }


                    /* Create info string */
                    info = CreateFileInfo(
                        name,
                        extension,
                        location,
                        sizeBytes,
                        File.GetCreationTime(path),
                        File.GetLastWriteTime(path),
                        File.GetLastAccessTime(path),
                        attributes
                        );
                }
                else
                {
                    name     = Path.GetFileNameWithoutExtension(path);
                    location = Path.GetDirectoryName(path);


                    /* Try to get the size of the directory and its attributes */
                    var           dirDirsInfo = new List <DirectoryInfo>(new DirectoryInfo(location).GetDirectories());
                    DirectoryInfo dirInfo     = dirDirsInfo.Find(dInfo => dInfo.Name == name);

                    attributes = dirInfo.Attributes;


                    // show info window to let user know that application is not frozen
                    Console.Clear();
                    CurrentShownInfo = new Info(
                        "Выполняется вычисление размера папки. Пожалуйста, подождите..."
                        );
                    ShowInfoWindow("Вычисление размера папки");


                    try
                    {
                        sizeBytes = dirInfo.EnumerateFiles("*", SearchOption.AllDirectories).Sum(fi => fi.Length);
                    }
                    catch (Exception e)
                    {
                        // exception will be thrown only if app has no rights to access the file or folder
                        // in that case just warn the user about it and show the size of the file as 'Неизвестно'

                        sizeBytes = -1;

                        ShowFileOperationDialog(
                            "Отказано в доступе к файлу",
                            "У приложения отсутствуют необходимые права для получения информации о размерах" +
                            $" папки {name}. Размер папки будет указан, как \"Неизвестно\".",
                            "продолжить",
                            null,
                            null
                            );
                    }


                    /* Create info string */
                    info = CreateDirInfo(
                        name,
                        location,
                        sizeBytes,
                        dirInfo.CreationTime,
                        attributes
                        );
                }
            }
            catch (Exception e)
            {
                ErrorLogger.LogError(e);

                var type = ExtraFunctional.IsDrive(path) ? "диске" : (ExtraFunctional.IsFile(path) ? "файле" : "папке");

                CurrentShownInfo = new Info(
                    $"Произошла ошибка при попытке получить информацию о {type}: {e.Message}",
                    InfoType.Error
                    );

                return;
            }


            CurrentShownInfo = new Info(info, InfoType.FileInfo);
        }
        private void Copy(params string[] args)
        {
            /* Check and parse arguments */
            var copiedPathArg      = args[0];
            var destinationPathArg = args[1];
            var replaceFileArg     = args[2];

            string copiedPath;
            string destinationPath;
            bool   replaceFiles;

            copiedPath      = ExtraFunctional.ParsePath(copiedPathArg, CurrentDirectory);
            destinationPath = ExtraFunctional.ParsePath(destinationPathArg, CurrentDirectory);

            // path can be null only if current directory is null
            if (copiedPath is null)
            {
                CurrentShownInfo = new Info(
                    "Невозможно использовать указанный путь. Укажите абсолютный путь.",
                    InfoType.Error
                    );
                return;
            }

            // check if copied file or directory exists
            if (!File.Exists(copiedPath) && !Directory.Exists(copiedPath))
            {
                CurrentShownInfo = new Info(
                    "Ошибка исполнения команды: указанный файл или директория не существует.",
                    InfoType.Error
                    );

                return;
            }


            var copiedObjIsFile = Path.HasExtension(copiedPath);


            // check if destination path is a directory that exists
            if (!Directory.Exists(destinationPath))
            {
                CurrentShownInfo = new Info(
                    "Ошибка исполнения команды: папки назначения не существует, либо путь указывал на файл.",
                    InfoType.Error
                    );

                return;
            }

            // parse extra arg
            replaceFiles = replaceFileArg is null ? false : bool.Parse(replaceFileArg);


            try
            {
                var newFilePath = Path.Combine(destinationPath, Path.GetFileName(copiedPath));

                if (copiedObjIsFile)
                {
                    // if file in destination folder exists and no extra arg was specified
                    // then warn the user
                    if (replaceFileArg is null && File.Exists(newFilePath))
                    {
                        CurrentShownInfo = new Info(
                            $"В папке назначения уже есть файл с именем {Path.GetFileName(newFilePath)}.\n" +
                            "Если вы желаете заменить файл в папке назначения, " +
                            "повторите команду с указанием аргумента замены как true:\n" +
                            $"cpy \"{copiedPath}\" \"{destinationPath}\" -rf true\n" +
                            "Если же вы желаете создать в папке назначения ещё один такой же файл, " +
                            "повторите команду с указанием аргумента замены как false:\n" +
                            $"cpy \"{copiedPath}\" \"{destinationPath}\" -rf false"
                            );

                        return;
                    }


                    // if replace file arg was specified as false, then create new name for the copied file
                    if (!replaceFiles && File.Exists(newFilePath))
                    {
                        var newFileName = ExtraFunctional.GetCopyFileName(
                            newFilePath,
                            Directory.GetFiles(destinationPath)
                            );

                        newFilePath = Path.Combine(destinationPath, newFileName);
                    }


                    File.Copy(copiedPath, newFilePath, replaceFiles);

                    CurrentShownInfo = Info.Empty;
                }
                else
                {
                    var newDirPath = Path.Combine(destinationPath, Path.GetFileName(copiedPath));

                    if (!Directory.Exists(newDirPath))
                    {
                        Directory.CreateDirectory(newDirPath);
                    }


                    // show a stub window so that the user knows that the program is not frozen
                    CurrentShownInfo = new Info("Идёт операция копирования файлов. Пожалуйста, подождите...");
                    ShowInfoWindow("Операция");


                    // recursively copy all files and dirs to another dir
                    var copiedSuccessfully = RecursiveFilesCopy(copiedPath, newDirPath, replaceFiles);

                    CurrentShownInfo = copiedSuccessfully ? Info.Empty : new Info("Операция копирования была прервана.");
                }
            }
            catch (Exception e)
            {
                ErrorLogger.LogError(e);

                CurrentShownInfo = new Info(
                    $"Произошла ошибка при попытке скопировать {(copiedObjIsFile ? "файл" : "папку")}: {e.Message}",
                    InfoType.Error
                    );
            }
        }
        private void Delete(params string[] args)
        {
            /* Check and parse arguments */
            var pathArg      = args[0];
            var recursiveArg = args[1];

            string path;
            bool   recursiveDeletion;

            path = ExtraFunctional.ParsePath(pathArg, CurrentDirectory);

            // path can be null only if current directory is null
            if (path is null)
            {
                CurrentShownInfo = new Info(
                    "Невозможно использовать указанный путь. Укажите абсолютный путь.",
                    InfoType.Error
                    );
                return;
            }

            if (!File.Exists(path) && !Directory.Exists(path))
            {
                CurrentShownInfo = new Info(
                    "Ошибка исполнения команды: указанный файл или директория не существует.",
                    InfoType.Error
                    );
                return;
            }

            recursiveDeletion = recursiveArg != null;


            var isFile = Path.HasExtension(path);

            try
            {
                if (isFile)
                {
                    File.Delete(path);
                }
                else
                {
                    if (Directory.GetFileSystemEntries(path).Length != 0 && recursiveDeletion == false)
                    {
                        CurrentShownInfo = new Info(
                            "Указанная директория не пуста. Если вы желаете удалить папку вместе со всем её " +
                            "содержимым, повторите команду, указав аргумент рекурсивного удаления:\n" +
                            $"del \"{path}\" -r true"
                            );

                        return;
                    }


                    // show a stub window so that the user knows that the program is not frozen
                    CurrentShownInfo = new Info("Идёт операция удаления файлов. Пожалуйста, подождите...");
                    ShowInfoWindow("Операция");


                    // recursively delete all files and dirs
                    var deletedSuccessfully = RecursiveFilesDeletion(path);

                    if (deletedSuccessfully)
                    {
                        Directory.Delete(path);
                    }


                    CurrentShownInfo = deletedSuccessfully ? Info.Empty : new Info("Операция удаления была прервана.");

                    if (CurrentDirectory == path)
                    {
                        CurrentDirectory = Path.GetDirectoryName(path.TrimEnd('\\'));
                    }
                }
            }
            catch (Exception e)
            {
                ErrorLogger.LogError(e);

                CurrentShownInfo = new Info(
                    $"Произошла ошибка при попытке удалить {(isFile ? "файл" : "папку")}: {e.Message}",
                    InfoType.Error
                    );
            }
        }
Example #48
0
        private static void UnzipFileToDirectory(string filePath, string unZipDirecotyPath, Action <float> progressAction, Action doneAction, Action errorAction)
        {
            ZipInputStream zipStream = null;
            FileStream     stream    = null;
            ZipFile        zipFile   = null;

            try
            {
                zipFile = new ZipFile(filePath);
                var entryCountDelta = 1f / zipFile.Count;
                zipFile.Close();
                zipFile = null;

                var currentEntryCount = 0;
                var currentProgress   = 0f;

                zipStream = new ZipInputStream(File.OpenRead(filePath));
                ZipEntry zipEntry = null;

                if ((zipEntry = zipStream.GetNextEntry()) != null)
                {
                    var buffer = new byte[4096];
                    while (zipEntry != null && GameRuntimeInfo.IsRunning)
                    {
                        string fileName = Path.GetFileName(zipEntry.Name);
                        if (!string.IsNullOrEmpty(fileName))
                        {
                            if (zipEntry.CompressedSize != 0)
                            {
                                var path    = Path.Combine(unZipDirecotyPath, zipEntry.Name);
                                var dirPath = Path.GetDirectoryName(path);
                                if (!Directory.Exists(dirPath))
                                {
                                    Directory.CreateDirectory(dirPath);
                                }

                                var fileSizeBase = 1f / zipEntry.Size;
                                var processSize  = 0;
                                stream = File.Create(path);
                                while (GameRuntimeInfo.IsRunning)
                                {
                                    int size = zipStream.Read(buffer, 0, buffer.Length);
                                    if (size > 0)
                                    {
                                        stream.Write(buffer, 0, size);
                                        processSize += size;
                                        progressAction((currentProgress + Mathf.Max(fileSizeBase * processSize * entryCountDelta, 0)) * 100);
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                                stream.Flush();
                                stream.Close();
                                stream = null;
                            }
                        }

                        ++currentEntryCount;
                        currentProgress = currentEntryCount * entryCountDelta;
                        //progressAction(currentProgress * 100);
                        zipEntry = zipStream.GetNextEntry();
                    }
                }
                doneAction();
            }
            catch (Exception e)
            {
                Debug.LogError("unzip file to directory error:" + e);
                errorAction();
            }
            finally
            {
                if (stream != null)
                {
                    stream.Flush();
                    stream.Close();
                }

                if (zipStream != null)
                {
                    zipStream.Flush();
                    zipStream.Close();
                }

                if (zipFile != null)
                {
                    zipFile.Close();
                }
            }
        }
 /// <summary>
 /// Configure the configuration settings.
 /// </summary>
 /// <param name="webHostBuilderContext">The context for building the host.</param>
 /// <param name="configurationBuilder">The Fluent builder for configurations.</param>
 private static void ConfigConfiguration(WebHostBuilderContext webHostBuilderContext, IConfigurationBuilder configurationBuilder)
 {
     configurationBuilder.SetBasePath(Directory.GetCurrentDirectory())
     .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
     .AddJsonFile($"appsettings.{webHostBuilderContext.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true);
 }
Example #50
0
 public override int GetNodeCount()
 {
     return(Directory.GetFileSystemEntries(this.DirectoryPath).Length);
 }
Example #51
0
        static int Main(string[] args)
        {
            // remember the working directory at start, as the game path could be relative to this path
            string InitialCurrentDirectory = Environment.CurrentDirectory;

            // set the working directory to the location of the application (so relative paths always work)
            Environment.CurrentDirectory = Path.GetDirectoryName(Application.ExecutablePath);

            AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);

            // A simple, top-level try-catch block
            try
            {
                if (!ParseCommandLine(ref args))
                {
                    Log("Usage: iPhonePackager <Command> <GameName> [RPCCommand &| Switch]");
                    Log("");
                    Log("Common commands:");
                    Log(" ... RepackageIPA GameName");
                    Log(" ... PackageIPA GameName");
                    Log(" ... PackageApp GameName");
                    Log(" ... Deploy PathToIPA");
                    Log(" ... RepackageFromStage GameName");
                    Log(" ... Devices");
                    Log(" ... Validate");
                    Log(" ... Install");
                    Log("");
                    Log("Configuration switches:");
                    Log("	 -stagedir <path>		  sets the directory to copy staged files from (defaults to none)");
                    Log("	 -project <path>		  path to the project being packaged");
                    Log("	 -provisioning <uuid>	  uuid of the provisioning selected");
                    Log("	 -compress=fast|best|none  packaging compression level (defaults to none)");
                    Log("	 -strip					strip symbols during packaging");
                    Log("	 -config				   game configuration (e.g., Shipping, Development, etc...)");
                    Log("	 -distribution			 packaging for final distribution");
                    Log("	 -createstub			   packaging stub IPA for later repackaging");
                    Log("	 -mac <MacName>			overrides the machine to use for any Mac operations");
                    Log("	 -arch <Architecture>	  sets the architecture to use (blank for default, -simulator for simulator builds)");
                    Log("	 -device <DeviceID>		sets the device to install the IPA on");
                    Log("");
                    Log("Commands: RPC, Clean");
                    Log("  StageMacFiles, GetIPA, Deploy, Install, Uninstall");
                    Log("");
                    Log("RPC Commands: SetExec, InstallProvision, MakeApp, DeleteIPA, Copy, Kill, Strip, Zip, GenDSYM");
                    Log("");
                    Log("Sample commandlines:");
                    Log(" ... iPhonePackager Deploy UDKGame Release");
                    Log(" ... iPhonePackager RPC SwordGame Shipping MakeApp");
                    return((int)ErrorCodes.Error_Arguments);
                }

                Log("Executing iPhonePackager " + String.Join(" ", args));
                Log("CWD: " + Directory.GetCurrentDirectory());
                Log("Initial Dir: " + InitialCurrentDirectory);
                Log("Env CWD: " + Environment.CurrentDirectory);

                // Ensure shipping configuration for final distributions
                if (Config.bForDistribution && (GameConfiguration != "Shipping"))
                {
                    Program.Warning("Distribution builds should be made in the Shipping configuration!");
                }

                // process the GamePath (if could be ..\Samples\MyDemo\ or ..\Samples\MyDemo\MyDemo.uproject
                GameName = Path.GetFileNameWithoutExtension(GamePath);
                if (GameName.Equals("UE4", StringComparison.InvariantCultureIgnoreCase) || GameName.Equals("Engine", StringComparison.InvariantCultureIgnoreCase))
                {
                    GameName = "UE4Game";
                }

                // setup configuration
                if (!Config.Initialize(InitialCurrentDirectory, GamePath))
                {
                    return((int)ErrorCodes.Error_Arguments);
                }

                switch (MainCommand.ToLowerInvariant())
                {
                case "validate":
                    // check to see if iTunes is installed
                    string dllPath = "";
                    if (Environment.OSVersion.Platform == PlatformID.MacOSX || Environment.OSVersion.Platform == PlatformID.Unix)
                    {
                        ProcessStartInfo StartInfo = new ProcessStartInfo("/usr/bin/xcode-select", "--print-path");
                        StartInfo.UseShellExecute        = false;
                        StartInfo.RedirectStandardOutput = true;
                        StartInfo.CreateNoWindow         = true;

                        using (Process LocalProcess = Process.Start(StartInfo))
                        {
                            StreamReader OutputReader = LocalProcess.StandardOutput;
                            // trim off any extraneous new lines, helpful for those one-line outputs
                            dllPath = OutputReader.ReadToEnd().Trim();
                        }
                    }
                    else
                    {
                        dllPath = Microsoft.Win32.Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Apple Inc.\\Apple Mobile Device Support\\Shared", "iTunesMobileDeviceDLL", null) as string;
                        if (String.IsNullOrEmpty(dllPath) || !File.Exists(dllPath))
                        {
                            dllPath = Microsoft.Win32.Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Apple Inc.\\Apple Mobile Device Support\\Shared", "MobileDeviceDLL", null) as string;
                        }
                    }
                    if (String.IsNullOrEmpty(dllPath) || (!File.Exists(dllPath) && !Directory.Exists(dllPath)))
                    {
                        Error("iTunes Not Found!!", (int)ErrorCodes.Error_SDKNotFound);
                    }
                    else
                    {
                        // validate there is a useable provision and cert
                        MobileProvision  Provision;
                        X509Certificate2 Cert;
                        bool             bHasOverrides;
                        bool             bNameMatch;
                        bool             foundPlist = CodeSignatureBuilder.FindRequiredFiles(out Provision, out Cert, out bHasOverrides, out bNameMatch);
                        if (!foundPlist)
                        {
                            Error("Could not find a valid plist file!!", (int)ErrorCodes.Error_InfoPListNotFound);
                        }
                        else if (!Config.bAutomaticSigning)
                        {
                            if (Provision == null && Cert == null)
                            {
                                Error("No Provision or cert found!!", (int)ErrorCodes.Error_ProvisionAndCertificateNotFound);
                            }
                            else if (Provision == null)
                            {
                                Error("No Provision found!!", (int)ErrorCodes.Error_ProvisionNotFound);
                            }
                            else if (Cert == null)
                            {
                                Error("No Signing Certificate found!!", (int)ErrorCodes.Error_CertificateNotFound);
                            }
                        }
                        else
                        {
                            if (Config.TeamID == null)
                            {
                                Error("No TeamID for automatic signing!!", (int)ErrorCodes.Error_ProvisionNotFound);
                            }
                        }
                    }
                    break;

                case "packageapp":
                    if (CheckArguments())
                    {
                        if (Config.bCreateStubSet)
                        {
                            Error("packageapp cannot be used with the -createstub switch");
                            Program.ReturnCode = (int)ErrorCodes.Error_Arguments;
                        }
                        else
                        {
                            // Create the .app on the Mac
                            CompileTime.CreateApplicationDirOnMac();
                        }
                    }
                    break;

                case "repackagefromstage":
                    if (CheckArguments())
                    {
                        if (Config.bCreateStubSet)
                        {
                            Error("repackagefromstage cannot be used with the -createstub switches");
                            Program.ReturnCode = (int)ErrorCodes.Error_Arguments;
                        }
                        else
                        {
                            bool bProbablyCreatedStub = Utilities.GetEnvironmentVariable("ue.IOSCreateStubIPA", true);
                            if (!bProbablyCreatedStub)
                            {
                                Warning("ue.IOSCreateStubIPA is currently FALSE, which means you may be repackaging with an out of date stub IPA!");
                            }

                            CookTime.RepackageIPAFromStub();
                        }
                    }
                    break;

                // this is the "super fast just move executable" mode for quick programmer iteration
                case "dangerouslyfast":
                    if (CheckArguments())
                    {
                        CompileTime.DangerouslyFastMode();
                    }
                    break;

                case "packageipa":
                    if (CheckArguments())
                    {
                        CompileTime.PackageIPAOnMac();
                    }
                    break;

                case "install":
                    GameName = "";
                    if (Config.bProvision)
                    {
                        ToolsHub.TryInstallingMobileProvision(Config.Provision, false);
                    }
                    if (Config.bCert)
                    {
                        ToolsHub.TryInstallingCertificate_PromptForKey(Config.Certificate, false);
                    }
                    CodeSignatureBuilder.FindCertificates();
                    CodeSignatureBuilder.FindProvisions(Config.OverrideBundleName);
                    break;

                case "certificates":
                {
                    CodeSignatureBuilder.FindCertificates();
                    CodeSignatureBuilder.FindProvisions(Config.OverrideBundleName);
                }
                break;

                case "resigntool":
                    RunInVisualMode(delegate { return(new GraphicalResignTool()); });
                    break;

                case "certrequest":
                    RunInVisualMode(delegate { return(new GenerateSigningRequestDialog()); });
                    break;

                case "gui":
                    RunInVisualMode(delegate { return(ToolsHub.CreateShowingTools()); });
                    break;

                case "devices":
                    ListDevices();
                    break;

                case "signing_match":
                {
                    MobileProvision  Provision;
                    X509Certificate2 Cert;
                    bool             bNameMatch;
                    bool             bHasOverrideFile;
                    if (CodeSignatureBuilder.FindRequiredFiles(out Provision, out Cert, out bHasOverrideFile, out bNameMatch) && Cert != null)
                    {
                        // print out the provision and cert name
                        Program.LogVerbose("CERTIFICATE-{0},PROVISION-{1}", Cert.FriendlyName, Path.GetFileName(Provision.FileName));
                    }
                    else
                    {
                        Program.LogVerbose("No matching Signing Data found!");
                    }
                }
                break;

                default:
                    // Commands by themself default to packaging for the device
                    if (CheckArguments())
                    {
                        ExecuteCommand(MainCommand, MainRPCCommand);
                    }
                    break;
                }
            }
            catch (Exception Ex)
            {
                Error("Application exception: " + Ex.ToString());
                if (ReturnCode == 0)
                {
                    Program.ReturnCode = (int)ErrorCodes.Error_Unknown;
                }
            }
            finally
            {
                if (DeploymentHelper.DeploymentServerProcess != null)
                {
                    DeploymentHelper.DeploymentServerProcess.Close();
                }
            }

            Environment.ExitCode = ReturnCode;
            return(ReturnCode);
        }
Example #52
0
        private void ProcessPackagedReferences(List <PackageReference> referencedPackages, out List <MetadataReference> referencesFromPackages, out Dictionary <string, string> packageDiscoveredPaths, CancellationToken cancellationToken)
        {
            //RFO: need to do the package discover first so it populates the
            referencesFromPackages = new List <MetadataReference>();

            packageDiscoveredPaths = new Dictionary <string, string>(StringComparer.InvariantCultureIgnoreCase);

            if (referencedPackages is object && referencedPackages.Any())
            {
                string nugetLocation = GetPackagesCacheFolder();

                var outputFolder = Path.GetDirectoryName(AssemblyLocation);

                var filesToCopy = new List <(string source, string destination)>();

                foreach (var rp in referencedPackages.GroupBy(p => p.PackageIdentity).OrderByDescending(p => p.Key.Version).Select(g => g.First()))
                {
                    cancellationToken.ThrowIfCancellationRequested();

                    string packageBasePath;

                    if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                    {
                        packageBasePath = Path.Combine(nugetLocation, rp.PackageIdentity.Id, rp.PackageIdentity.Version.ToString());
                    }
                    else
                    {
                        //Package path is lower-case on Linux platforms
                        packageBasePath = Path.Combine(nugetLocation, rp.PackageIdentity.Id.ToLowerInvariant(), rp.PackageIdentity.Version.ToString().ToLowerInvariant());
                    }

                    if (Directory.Exists(packageBasePath))
                    {
                        Logger.ZLogInformation($"NuGet: Importing package {rp.PackageIdentity.Id} version {rp.PackageIdentity.Version}");

                        var foundLibs = new List <string>();
                        foreach (var file in Directory.EnumerateFiles(Path.Combine(packageBasePath, "lib", rp.TargetFramework.GetShortFolderName()), "*.dll", SearchOption.AllDirectories))
                        {
                            referencesFromPackages.Add(MetadataReference.CreateFromFile(file));
                            _packagedFiles[Path.GetFileName(file)] = file;
                            foundLibs.Add(file);
                        }

                        foreach (var source in Directory.EnumerateFiles(Path.Combine(packageBasePath, "lib", rp.TargetFramework.GetShortFolderName()), "*.*", SearchOption.AllDirectories))
                        {
                            var target = Path.Combine(outputFolder, Path.GetFileName(source));
                            filesToCopy.Add((source, target));
                        }

                        var contentFolder = Path.Combine(packageBasePath, "content");
                        if (Directory.Exists(contentFolder))
                        {
                            foreach (var source in Directory.EnumerateFiles(contentFolder, "*.*", SearchOption.AllDirectories))
                            {
                                var target = Path.Combine(outputFolder, Path.GetFileName(source));
                                filesToCopy.Add((source, target));
                            }
                        }

                        packageDiscoveredPaths[rp.PackageIdentity.Id] = foundLibs.First();

                        if (string.Equals(rp.PackageIdentity.Id, CS.NS.H5, StringComparison.InvariantCultureIgnoreCase))
                        {
                            H5Location = foundLibs.Single(); //H5 should be the single dll in the file
                        }
                    }
                    else
                    {
                        Logger.ZLogError($"NuGet package not found on path '{packageBasePath}': {rp.PackageIdentity.Id} version {rp.PackageIdentity.Version}");
                        throw new Exception($"NuGet package not found on path '{packageBasePath}': {rp.PackageIdentity.Id} version {rp.PackageIdentity.Version}");
                    }
                }

                if (filesToCopy.Any())
                {
                    Task.WaitAll(filesToCopy.Select(async(copy) =>
                    {
                        cancellationToken.ThrowIfCancellationRequested();

                        Logger.ZLogInformation($"NuGet: Copying lib file '{copy.source}' to '{copy.destination}'");
                        await CopyFileAsync(copy.source, copy.destination).ConfigureAwait(false);
                    }).ToArray());
                }
            }
        }
Example #53
0
        protected override void ProcessRecord()
        {
            try
            {
                if (!Directory.Exists(ExportsFolder))
                {
                    throw new ArgumentException($"Exports folder '{ExportsFolder}' does not exist");
                }

                var exportDirectories = Directory.GetDirectories(ExportsFolder);
                if (!exportDirectories.Any())
                {
                    exportDirectories = new[] { ExportsFolder };
                }
                var utilFile = Path.Combine(OutputFolder, "utils.ps1");
                if (!File.Exists(utilFile))
                {
                    var sc = new StringBuilder();
                    sc.AppendLine(@"function RandomString([bool]$allChars, [int32]$len) {
    if ($allChars) {
        return -join ((33..126) | Get-Random -Count $len | % {[char]$_})
    } else {
        return -join ((48..57) + (97..122) | Get-Random -Count $len | % {[char]$_})
    }
}
$env = @{}
function setupEnv() {
    # Preload subscriptionId and tenant from context, which will be used in test
    # as default. You could change them if needed.
    $env.SubscriptionId = (Get-AzContext).Subscription.Id
    $env.Tenant = (Get-AzContext).Tenant.Id
    # For any resources you created for test, you should add it to $env here.
    $envFile = 'env.json'
    if ($TestMode -eq 'live') {
        $envFile = 'localEnv.json'
    }
    set-content -Path (Join-Path $PSScriptRoot $envFile) -Value (ConvertTo-Json $env)
}
function cleanupEnv() {
    # Clean resources you create for testing
}
");
                    File.WriteAllText(utilFile, sc.ToString());
                }
                foreach (var exportDirectory in exportDirectories)
                {
                    var outputFolder = OutputFolder;
                    if (exportDirectory != ExportsFolder)
                    {
                        outputFolder = Path.Combine(OutputFolder, Path.GetFileName(exportDirectory));
                        Directory.CreateDirectory(outputFolder);
                    }

                    var variantGroups = GetScriptCmdlets(exportDirectory)
                                        .SelectMany(fi => fi.ToVariants())
                                        .Where(v => !v.IsDoNotExport)
                                        .GroupBy(v => v.CmdletName)
                                        .Select(vg => new VariantGroup(ModuleName, vg.Key, vg.Select(v => v).ToArray(), outputFolder, isTest: true))
                                        .Where(vtg => !File.Exists(vtg.FilePath) && (IncludeGenerated || !vtg.IsGenerated));

                    foreach (var variantGroup in variantGroups)
                    {
                        var sb = new StringBuilder();
                        sb.AppendLine(@"$loadEnvPath = Join-Path $PSScriptRoot 'loadEnv.ps1'
if (-Not (Test-Path -Path $loadEnvPath)) {
    $loadEnvPath = Join-Path $PSScriptRoot '..\loadEnv.ps1'
}
. ($loadEnvPath)"
                                      );
                        sb.AppendLine($@"$TestRecordingFile = Join-Path $PSScriptRoot '{variantGroup.CmdletName}.Recording.json'");
                        sb.AppendLine(@"$currentPath = $PSScriptRoot
while(-not $mockingPath) {
    $mockingPath = Get-ChildItem -Path $currentPath -Recurse -Include 'HttpPipelineMocking.ps1' -File
    $currentPath = Split-Path -Path $currentPath -Parent
}
. ($mockingPath | Select-Object -First 1).FullName
");

                        sb.AppendLine($"Describe '{variantGroup.CmdletName}' {{");
                        var variants = variantGroup.Variants
                                       .Where(v => IncludeGenerated || !v.Attributes.OfType <GeneratedAttribute>().Any())
                                       .ToList();

                        foreach (var variant in variants)
                        {
                            sb.AppendLine($"{Indent}It '{variant.VariantName}' -skip {{");
                            sb.AppendLine($"{Indent}{Indent}{{ throw [System.NotImplementedException] }} | Should -Not -Throw");
                            var variantSeparator = variants.IndexOf(variant) == variants.Count - 1 ? String.Empty : Environment.NewLine;
                            sb.AppendLine($"{Indent}}}{variantSeparator}");
                        }
                        sb.AppendLine("}");

                        File.WriteAllText(variantGroup.FilePath, sb.ToString());
                    }
                }
            }
            catch (Exception ee)
            {
                Console.WriteLine($"${ee.GetType().Name}/{ee.StackTrace}");
                throw ee;
            }
        }
Example #54
0
        /// <summary>
        /// Extracts the zip.
        /// </summary>
        /// <param name="zip">The zip.</param>
        /// <param name="rootFolder">The root folder.</param>
        /// <param name="newFolder">The new folder.</param>
        /// <param name="matchPath">The match path.</param>
        private void ExtractZip(string zip, string rootFolder, string newFolder, string matchPath)
        {
            try {
                long totalEntries = 0;
                using (ZipFile z = new ZipFile(zip)) {
                    totalEntries = z.Count;
                    this.downloadProgress.SetMaximum((int)z.Count);
                    this.downloadProgress.SetMinimum(0);
                    this.downloadProgress.SetValue(0);
                    z.Close( );
                }
                using (FileStream zfs = new FileStream(zip, FileMode.Open, FileAccess.Read)) {
                    long currentEntryIndex = 0;

                    using (ZipInputStream zis = new ZipInputStream(zfs)) {
                        ZipEntry ze = zis.GetNextEntry( );
                        while (ze != null)
                        {
                            string entryPath         = Path.GetDirectoryName(ze.Name).Replace(rootFolder, newFolder);
                            string fullDirectoryPath = Path.Combine(SdkPath, entryPath);

                            string fileName = Path.GetFileName(ze.Name);
                            string fullPath = Path.Combine(fullDirectoryPath, fileName);

                            if (!fullPath.Contains(matchPath))
                            {
                                ze = zis.GetNextEntry( );
                                currentEntryIndex++;
                                continue;
                            }

                            if (!Directory.Exists(fullDirectoryPath))
                            {
                                Directory.CreateDirectory(fullDirectoryPath);
                            }

                            this.downloadStatus.SetText(string.Format(CultureInfo.InvariantCulture, Properties.Resources.ExtractingFileFormat, ze.Name));
                            if (ze.IsFile)
                            {
                                using (FileStream fs = new FileStream(fullPath, FileMode.Create, FileAccess.Write, FileShare.Read)) {
                                    int    bread  = 0;
                                    byte[] buffer = new byte[2048];
                                    while ((bread = zis.Read(buffer, 0, buffer.Length)) > 0)
                                    {
                                        fs.Write(buffer, 0, bread);
                                    }
                                    fs.Close( );
                                }
                            }
                            this.downloadProgress.SetValue((int)currentEntryIndex);
                            ze = zis.GetNextEntry( );
                            currentEntryIndex++;
                        }
                        zis.Close( );
                    }
                    zfs.Close( );
                    this.downloadProgress.SetValue(0);
                    this.downloadStatus.SetText(string.Empty);
                }
            } catch (Exception ex) {
                throw;
            }
        }
Example #55
0
        static void Main(string[] args)
        {
            string        currentDircetory = Directory.GetCurrentDirectory();
            DirectoryInfo directory        = new DirectoryInfo(currentDircetory);
            var           fileName         = Path.Combine(directory.FullName, "SoccerGameResults.csv");
            var           fileContents     = ReadSoccerResults(fileName);

            fileName = Path.Combine(directory.FullName, "players.json");
            var players       = DeserializePlayers(fileName);
            var topTenPlayers = GetTopTenPlayers(players);


            foreach (var player in players)
            {
                Console.WriteLine(
                    String.Format(
                        "Team: {0}, ID: {1}, First name: {2}, Last name: {3}, Points per game: {4}",

                        player.TeamName,
                        player.Id,
                        player.FirstName,
                        player.LastName,
                        player.PointsPerGame
                        )
                    );
            }

            Console.WriteLine("\n The top ten players of the season are: \n");

            foreach (var player in topTenPlayers)
            {
                List <NewsResult> newsResults       = GetNewsForPlayer(string.Format("{0} {1}", player.FirstName, player.LastName));
                SentimentResponse sentimentResponse = GetSentimentResponse(newsResults);

                foreach (var sentiment in sentimentResponse.Sentiments)
                {
                    foreach (var newsResult in newsResults)
                    {
                        if (newsResult.HeadLine == sentiment.Id)
                        {
                            double score;
                            if (double.TryParse(sentiment.Score, out score))
                            {
                                newsResult.SentimentScore = score;
                            }
                            break;
                        }
                    }
                }

                foreach (var result in newsResults)
                {
                    Console.WriteLine(
                        string.Format(
                            "Sentiment score: {0:P}, \n Date: {1:f},\n Headline: {2}, \n Summary: \n\n {3} \r\n",
                            result.SentimentScore,
                            result.DatePublished,
                            result.HeadLine,
                            result.Summary
                            ));
                    Console.ReadKey();
                }
            }
            //fileName = Path.Combine(directory.FullName, "topTenPlayers.json");
            //SerialzePlayersToFile(topTenPlayers, fileName);
        }
Example #56
0
        public static String SubirImagen(FileUpload subirImagen, int id)
        {
            //comprueba si hay archivo
            if (subirImagen.HasFile)
            {
                //comprueba si es una imagen
                if (subirImagen.PostedFile.ContentType == "image/jpeg" || subirImagen.PostedFile.ContentType == "image/gif" || subirImagen.PostedFile.ContentType == "image/png")
                {
                    //comprueba si pesa menos de 15mB.
                    if (subirImagen.PostedFile.ContentLength < 15985760)
                    {
                        //crea el nombre de la imagen con la fecha del momento + el id + la extension.
                        DateTime fecha        = DateTime.Now;
                        string   ext          = Path.GetExtension(subirImagen.FileName);
                        string   nombreImagen = id + "_" + fecha.Day.ToString() + fecha.Month.ToString() + fecha.Year.ToString() + "_" + fecha.Hour.ToString() + fecha.Minute.ToString() + fecha.Second.ToString() + fecha.Millisecond.ToString() + ext;

                        //comprueba si existe el directorio en el servidor, sino lo crea.
                        if (!Directory.Exists(System.Web.HttpContext.Current.Server.MapPath(@"IMAGENES_SUBIDAS\" + id)))
                        {
                            ;
                        }
                        {
                            Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath(@"IMAGENES_SUBIDAS\" + id));
                        }

                        //guardamos la ruta de la carpeta de imagenes del usuario.
                        string carpeta = System.Web.HttpContext.Current.Server.MapPath(@"IMAGENES_SUBIDAS\" + id + "\\");

                        //creamos un bitmap con la imagen subida.
                        Bitmap BMPoriginal = new Bitmap(subirImagen.FileContent);

                        //variables para redimensionar la imagen.
                        int    newHeight = 0, newWidth = 0;
                        Bitmap BMP;

                        //si es una imagen horizontal:
                        //si la imagen es mas ancha que 1600 calcula la proporcion de la imagen y
                        //la nueva altura, y la guarda en el bitmap definitivo con las medidas
                        //establecidas para que sea maximo 1600 de ancho, si es menos
                        //ancha que 1600 la guardamos tal cual.
                        if (BMPoriginal.Width >= BMPoriginal.Height)
                        {
                            if (BMPoriginal.Width > 1600)
                            {
                                decimal origWidth  = BMPoriginal.Width;
                                decimal origHeight = BMPoriginal.Height;
                                decimal imgRatio   = origHeight / origWidth;
                                newWidth = 1600; //ANCHO PREDEFINIDO
                                decimal newHeight_temp = newWidth * imgRatio;
                                newHeight = Convert.ToInt16(newHeight_temp);

                                BMP = new Bitmap(BMPoriginal, newWidth, newHeight);
                            }
                            else
                            {
                                BMP = BMPoriginal;
                            }
                        }
                        //else si es una imagen vertical:
                        //si la imagen es mas alta que 1600 calcula la proporcion de la imagen y
                        //el nuevo ancho, y la guarda en el bitmap definitivo con las medidas
                        //establecidas para que sea maximo 1600 de alto, si es menos
                        //alta que 1600 la guardamos tal cual.
                        else
                        {
                            if (BMPoriginal.Height > 1600)
                            {
                                decimal origWidth  = BMPoriginal.Width;
                                decimal origHeight = BMPoriginal.Height;
                                decimal imgRatio   = origWidth / origHeight;
                                newHeight = 1600; //Alto PREDEFINIDO
                                decimal newWidth_temp = newHeight * imgRatio;
                                newWidth = Convert.ToInt16(newWidth_temp);

                                BMP = new Bitmap(BMPoriginal, newWidth, newHeight);
                            }
                            else
                            {
                                BMP = BMPoriginal;
                            }
                        }

                        //convertimos el bitmap en un grafico y le aplicamos unos retoques de calidad.
                        Graphics Grafico = Graphics.FromImage(BMP);
                        Grafico.SmoothingMode     = SmoothingMode.AntiAlias;
                        Grafico.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        Grafico.DrawImage(BMPoriginal, 0, 0, newWidth, newHeight);

                        //probamos de guardar la imagen en el servidor, y capturamos excepcion.
                        try
                        {
                            BMP.Save(carpeta + nombreImagen);
                        }
                        catch (ExternalException ex)
                        {
                            return(ex.InnerException.Message);
                        }

                        //vaciamos los objetos usados.
                        BMPoriginal.Dispose();
                        BMP.Dispose();
                        Grafico.Dispose();

                        //retornamos la ruta exacta de la imagen para poder guardala en la base de datos.
                        return("IMAGENES_SUBIDAS\\" + id + "\\" + nombreImagen);
                    }
                    //distintos mensajes de error de los ifs del principio de la funcion.
                    else
                    {
                        return("ERROR: Tamaño maximo 15MB.");
                    }
                }
                else
                {
                    return("ERROR: El archivo seleccionado no es una imagen.");
                }
            }
            else
            {
                return("ERROR: Selecciona una imagen porfavor");
            }
        }
        protected async Task<string> AssertGenerateRightClickAsync(string projectName, UserSelectionContext context, bool emptyProject, List<string> excludedGroupIdentity = null)
        {
            BaseGenAndBuildFixture.SetCurrentLanguage(context.Language);
            BaseGenAndBuildFixture.SetCurrentPlatform(context.Platform);
            var path = Path.Combine(_fixture.TestNewItemPath, projectName, projectName);

            GenContext.Current = new FakeContextProvider
            {
                ProjectName = projectName,
                DestinationPath = path,
                GenerationOutputPath = path,
            };

            var userSelection = _fixture.SetupProject(context);
            var appModel = context.GetAppModel();

            if (!emptyProject)
            {
                var templates = _fixture.Templates().Where(
                    t => t.GetTemplateType().IsItemTemplate()
                    && (t.GetProjectTypeList().Contains(context.ProjectType) || t.GetProjectTypeList().Contains(All))
                    && (t.GetFrontEndFrameworkList().Contains(context.FrontEndFramework) || t.GetFrontEndFrameworkList().Contains(All))
                    && t.GetPlatform() == context.Platform
                    && (string.IsNullOrEmpty(appModel) || t.GetPropertyBagValuesList("appmodel").Contains(appModel) || t.GetPropertyBagValuesList("appmodel").Contains(All))
                    && (excludedGroupIdentity == null || (!excludedGroupIdentity.Contains(t.GroupIdentity)))
                    && !t.GetIsHidden());

                var templatesInfo = GenContext.ToolBox.Repo.GetTemplatesInfo(templates, context);

                _fixture.AddItems(userSelection, templatesInfo, BaseGenAndBuildFixture.GetDefaultName);
            }

            await NewProjectGenController.Instance.UnsafeGenerateProjectAsync(userSelection);

            var project = Path.Combine(_fixture.TestNewItemPath, projectName);

            // Assert on project
            Assert.True(Directory.Exists(project));

            int emptyProjecFileCount = Directory.GetFiles(project, "*.*", SearchOption.AllDirectories).Count();
            Assert.True(emptyProjecFileCount > 2);

            var rightClickTemplates = _fixture.Templates().Where(
                t => t.GetTemplateType().IsItemTemplate()
                && (t.GetProjectTypeList().Contains(context.ProjectType) || t.GetProjectTypeList().Contains(All))
                && (t.GetFrontEndFrameworkList().Contains(context.FrontEndFramework) || t.GetFrontEndFrameworkList().Contains(All))
                && t.GetPlatform() == context.Platform
                && (string.IsNullOrEmpty(appModel) || t.GetPropertyBagValuesList("appmodel").Contains(appModel) || t.GetPropertyBagValuesList("appmodel").Contains(All))
                && !t.GetIsHidden()
                && (excludedGroupIdentity == null || (!excludedGroupIdentity.Contains(t.GroupIdentity)))
                && t.GetRightClickEnabled());

            await AddRightClickTemplatesAsync(path, rightClickTemplates, projectName, context.ProjectType, context.FrontEndFramework, context.Platform, context.Language);

            var finalProjectPath = Path.Combine(_fixture.TestNewItemPath, projectName);
            int finalProjectFileCount = Directory.GetFiles(finalProjectPath, "*.*", SearchOption.AllDirectories).Count();

            if (emptyProject)
            {
                Assert.True(finalProjectFileCount > emptyProjecFileCount);
            }
            else
            {
                Assert.True(finalProjectFileCount == emptyProjecFileCount);
            }

            return finalProjectPath;
        }
Example #58
0
        void Auto(string[] args)
        {
            Logger.ConsoleExceptions = true;

            var serverName = Prompt("Server");
            var defaultPath = $@"\\{serverName}\c$\inetpub\logs\LogFiles";
            string path;
            do
            {
                path = Prompt($"Path ({defaultPath})", v => true).NullIfEmpty() ?? defaultPath;
                if (Directory.Exists(path))
                    break;
                Console.WriteLine($"  [{path}] is not a valid path!");
            } while (true);

            var redirectionDoc = XDocument.Load($@"\\{serverName}\c$\windows\system32\inetsrv\config\redirection.config");
            Console.WriteLine("redirection.config loaded: " + (redirectionDoc != null));
            var redNote = redirectionDoc.Root.Element("configurationRedirection");
            var configPath = string.Equals(redNote?.Attribute("enabled")?.Value, "true", StringComparison.OrdinalIgnoreCase)
                ? redNote.Attribute("path").Value
                : $@"\\{serverName}\c$\windows\system32\inetsrv\config";
            Console.WriteLine("Config path: " + configPath);

            var sites = XDocument.Load(Path.Combine(configPath, "applicationHost.config"))
                .Root
                .Element("system.applicationHost")
                .Element("sites")
                .Elements("site");

            var siteBindings = sites
                .ToDictionary(
                    e => e.Attribute("id").Value, 
                    e => new
                    {
                        Name = e.Attribute("name").Value,
                        DefaultHost = e.Element("bindings")
                            .Elements("binding")
                            .Select(be => be.Attribute("bindingInformation").Value)
                            .Select(bi => bi.Split(':').Last())
                            .GroupBy(bi => bi.ToLower())
                            .OrderByDescending(g => g.Count())
                            .First()
                            .Key,
                    });
            foreach (var binding in siteBindings)
                Console.WriteLine($"Found site: {binding.Key}: {binding.Value.Name}");

            var ftpSites = Directory.GetDirectories(path, "FTPSVC*")
                .Select(ftpPath =>
                {
                    var id = Path.GetFileName(ftpPath).Substring("FTPSVC".Length);
                    if (!siteBindings.ContainsKey(id))
                    {
                        Console.WriteLine($"  [{id}]: Unknown FTP site!");
                        return null;
                    }
                    return new
                    {
                        id = id,
                        path = ftpPath,
                        siteName = siteBindings[id].Name,
                    };
                })
                .Where(s => s != null)
                .ToArray();
            var w3Sites = Directory.GetDirectories(path, "W3SVC*")
                .Select(w3Path =>
                {
                    var id = Path.GetFileName(w3Path).Substring("W3SVC".Length);
                    if (!siteBindings.ContainsKey(id))
                    {
                        Console.WriteLine($"  [{id}]: Unknown W3 site!");
                        return null;
                    }
                    //var defaultHost = Prompt($"Host for {siteBindings[id]} ({id})", v => true);
                    return new
                    {
                        id = id,
                        path = w3Path,
                        siteName = siteBindings[id].Name,
                        defaultHost = siteBindings[id].DefaultHost,
                    };
                })
                .Where(s => s != null)
                .ToArray();

            Console.WriteLine();
            Console.WriteLine("FTP Sites: " + ftpSites.Length);
            Console.WriteLine("W3 Sites: " + w3Sites.Length);
            if (ftpSites.Length == 0 && w3Sites.Length == 0)
            {
                Console.WriteLine("  No sites found!");
                return;
            }

            var proceed = Prompt("Proceed (y|n)", v => v.ToLower() == "y" || v.ToLower() == "n");
            if (!proceed.Equals("y"))
                return;

            var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
            Console.WriteLine(connectionString);
            var sw = Stopwatch.StartNew();
            foreach (var site in ftpSites)
            {
                ProcessLogs<FtpLogItem>(serverName, site.siteName, null, connectionString, "flexlabs.IIS_FtpLogs", Directory.GetFiles(site.path, "*.log"));
            }

            foreach (var site in w3Sites)
            {
                ProcessLogs<W3LogItem>(serverName, site.siteName, site.defaultHost, connectionString, "flexlabs.IIS_WebLogs", Directory.GetFiles(site.path, "*.log"));
            }

            sw.Stop();
            Console.WriteLine($"Uploaded in {sw.Elapsed}");
            Console.WriteLine($"Processed {totalCounter.ToString("N0")} logs at {(totalCounter / sw.Elapsed.TotalSeconds).ToString("N2")} logs/sec");
        }
        private object SetupServiceConfig(InstanceContext instanceContext, Message message)
        {
            object obj2 = new CServiceConfig();
            IServiceThreadPoolConfig config = (IServiceThreadPoolConfig)obj2;

            switch (this.info.ThreadingModel)
            {
            case ThreadingModel.MTA:
                config.SelectThreadPool(System.ServiceModel.ComIntegration.ThreadPoolOption.MTA);
                break;

            case ThreadingModel.STA:
                config.SelectThreadPool(System.ServiceModel.ComIntegration.ThreadPoolOption.STA);
                break;

            default:
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.UnexpectedThreadingModel());
            }
            config.SetBindingInfo(System.ServiceModel.ComIntegration.BindingOption.BindingToPoolThread);
            if (this.info.HasUdts())
            {
                IServiceSxsConfig config2 = obj2 as IServiceSxsConfig;
                if (config2 == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.QFENotPresent());
                }
                lock (manifestLock)
                {
                    string directory = string.Empty;
                    try
                    {
                        directory = Path.GetTempPath();
                    }
                    catch (Exception exception)
                    {
                        if (Fx.IsFatal(exception))
                        {
                            throw;
                        }
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.CannotAccessDirectory(directory));
                    }
                    string path = directory + this.info.AppID.ToString() + @"\";
                    if (!Directory.Exists(path))
                    {
                        try
                        {
                            Directory.CreateDirectory(path);
                        }
                        catch (Exception exception2)
                        {
                            if (Fx.IsFatal(exception2))
                            {
                                throw;
                            }
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(Error.CannotAccessDirectory(path));
                        }
                        Guid[] assemblies = this.info.Assemblies;
                        ComIntegrationManifestGenerator.GenerateManifestCollectionFile(assemblies, path + manifestFileName + ".manifest", manifestFileName);
                        foreach (Guid guid in assemblies)
                        {
                            System.Type[] types = this.info.GetTypes(guid);
                            if (types.Length > 0)
                            {
                                string assemblyName = guid.ToString();
                                ComIntegrationManifestGenerator.GenerateWin32ManifestFile(types, path + assemblyName + ".manifest", assemblyName);
                            }
                        }
                    }
                    config2.SxsConfig(CSC_SxsConfig.CSC_NewSxs);
                    config2.SxsName(manifestFileName + ".manifest");
                    config2.SxsDirectory(path);
                }
            }
            if (this.info.PartitionId != DefaultPartitionId)
            {
                IServicePartitionConfig config3 = (IServicePartitionConfig)obj2;
                config3.PartitionConfig(System.ServiceModel.ComIntegration.PartitionOption.New);
                config3.PartitionID(this.info.PartitionId);
            }
            IServiceTransactionConfig config4 = (IServiceTransactionConfig)obj2;

            config4.ConfigureTransaction(TransactionConfig.NoTransaction);
            if ((this.info.TransactionOption == TransactionOption.Required) || (this.info.TransactionOption == TransactionOption.Supported))
            {
                Transaction messageTransaction = null;
                messageTransaction = MessageUtil.GetMessageTransaction(message);
                if (messageTransaction != null)
                {
                    System.ServiceModel.ComIntegration.TransactionProxy item = new System.ServiceModel.ComIntegration.TransactionProxy(this.info.AppID, this.info.Clsid);
                    item.SetTransaction(messageTransaction);
                    instanceContext.Extensions.Add(item);
                    IServiceSysTxnConfig config5 = (IServiceSysTxnConfig)config4;
                    IntPtr pITxByot = TransactionProxyBuilder.CreateTransactionProxyTearOff(item);
                    config5.ConfigureBYOTSysTxn(pITxByot);
                    Marshal.Release(pITxByot);
                }
            }
            return(obj2);
        }
 public void OpenOriginalSbfres(string path)
 {
     if (File.Exists(path) && Path.GetExtension(path).ToLower() == ".sbfres" || Directory.Exists(path))
     {
         sourceSbfresPath = path;
         if (File.Exists(sourceActorPath) || Directory.Exists(sourceActorPath))
         {
             btn_RebuildActor.Enabled = true;
         }
         else
         {
             btn_RebuildActor.Enabled = false;
         }
     }
 }