Esempio n. 1
0
        static void Main(string[] args)
        {
            Trace.Listeners.Add(new ConsoleTraceListener());

            var login = "******";
            var password = "******";
            var directory = "Your directory";
            var localStorage = new LocalStorage(directory);
            var vkStorage = new VkStorage(login, password);
            var synchronizer = new Synchronizer(localStorage, vkStorage);

            Console.ReadLine();
        }
 private void AllocateLocals(LambdaCompiler lc)
 {
     foreach (ParameterExpression expression in this.GetVariables())
     {
         if (((VariableStorageKind) this.Definitions[expression]) == VariableStorageKind.Local)
         {
             Storage storage;
             if (this.IsMethod && lc.Parameters.Contains(expression))
             {
                 storage = new ArgumentStorage(lc, expression);
             }
             else
             {
                 storage = new LocalStorage(lc, expression);
             }
             this._locals.Add(expression, storage);
         }
     }
 }
Esempio n. 3
0
        public DataEditWindow(Instrument instrument)
        {
            InitializeComponent();
            DataContext = this;

            Data = new ObservableCollection<OHLCBar>();

            //grab and update the instrument
            using (var context = new MyDBContext())
            {
                context.Instruments.Attach(instrument);
                context.Entry(instrument).Reload();
                TheInstrument = instrument;
            }

            StartTime = new DateTime(1950, 1, 1, 0, 0, 0, 0);
            EndTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0, 0);

            if (!TheInstrument.ID.HasValue) return;

            //grab the data info
            using (var localStorage = new LocalStorage())
            {
                var storageInfo = localStorage.GetStorageInfo(TheInstrument.ID.Value);

                if (storageInfo.Count == 0) //if it doesn't have any data, we just exit
                {
                    MessageBox.Show("This instrument has no data.");
                    Hide();
                }
                else
                {
                    foreach (StoredDataInfo s in storageInfo) //fill the resolution box
                    {
                        ResolutionComboBox.Items.Add(s.Frequency);
                    }
                }
            }
        }
		private static void SaveLogin(Request request)
		{
			"Saving Target login information.".Debug();

			var dir = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory;
			if (dir == null) throw new Exception("Could not access application folder.");

			var storagefile = Path.Combine(dir.FullName, "config-edit.json");
			var localStorage = new LocalStorage<Configuration>(storagefile);
			var config = File.Exists(storagefile) ? localStorage.Load() : new Configuration();

			config.Target = new ServerConfiguration
			{
				Type = request.Type,
				Protocol = request.Protocol,
				Host = request.Host,
				User = request.User,
				Password = request.Password
			};

			localStorage.Save(config);
		}
		private void SaveLogin(LeanKitAccountAuth account)
		{
			"Saving LeanKit login information...".Debug();

			try
			{
				var dir = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory;
				if (dir == null) throw new Exception("Could not access current directory.");
				var curFolder = dir.FullName;
				var storagefile = Path.Combine(curFolder, "config-edit.json");
				var localStorage = new LocalStorage<Configuration>(storagefile);
				var config = File.Exists(storagefile) ? localStorage.Load() : new Configuration();

				config.LeanKit = new ServerConfiguration
				{
					Host = account.Hostname,
					User = account.Username,
					Password = account.Password
				};
				localStorage.Save(config);
			}
			catch (Exception ex)
			{
				string.Format("Error saving login creditials: {0}", ex.Message).Error(ex);
				throw;
			}
		}
Esempio n. 6
0
        /// <summary>
        /// The methods provided in this section are simply used to allow
        /// NavigationHelper to respond to the page's navigation methods.
        /// <para>
        /// Page specific logic should be placed in event handlers for the
        /// <see cref="NavigationHelper.LoadState"/>
        /// and <see cref="NavigationHelper.SaveState"/>.
        /// The navigation parameter is available in the LoadState method
        /// in addition to page state preserved during an earlier session.
        /// </para>
        /// </summary>
        /// <param name="e">Provides data for navigation methods and event
        /// handlers that cannot cancel the navigation request.</param>
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            DisplayInformation.AutoRotationPreferences = DisplayOrientations.Portrait; //Restricting Rotation

            Pivot.SelectedIndex = PivotSelectedIndex;
            if (e.NavigationMode == NavigationMode.Back)
            {
                switch (Pivot.SelectedIndex)
                {
                case 0:
                    break;

                case 1:
                    ((SpeakerDetailsPageViewModel)this.DataContext).GetBlogsForSpeaker();
                    break;

                case 2:
                    ((SpeakerDetailsPageViewModel)this.DataContext).GetUpcommingSessions();
                    break;

                default:
                    break;
                }
            }

            if (e.Parameter != null)
            {
                var trackSpeaker = JsonConvert.DeserializeObject <TrackSpeaker>(e.Parameter.ToString());

                if (trackSpeaker != null)
                {
                    //_speakerDetailsPageViewModel.Speaker = trackSpeaker;
                    //this.DataContext = _speakerDetailsPageViewModel;
                    //_speakerDetailsPageViewModel.GetSpeakerDetails(trackSpeaker);
                    ((SpeakerDetailsPageViewModel)this.DataContext).Speaker = trackSpeaker;
                    await((SpeakerDetailsPageViewModel)this.DataContext).GetSpeakerDetails(trackSpeaker);
                    ((SpeakerDetailsPageViewModel)this.DataContext).GetBlogsForSpeaker();
                }


                var data = await LocalStorage.ReadJsonFromFile <List <TrackSpeaker> >("followedSpeakers");

                if (data == null)
                {
                    data = new List <TrackSpeaker>();
                }

                var viewModel = this.DataContext as SpeakerDetailsPageViewModel;
                if (viewModel == null)
                {
                    return;
                }

                if (data.FirstOrDefault(x => x.SpeakerId == viewModel.Speaker.SpeakerId) != null)
                {
                    viewModel.Speaker.IsFollowed = true;
                }
            }

            //if (e.NavigationMode == NavigationMode.Back || e.NavigationMode == NavigationMode.Refresh)
            //{
            //    ((SpeakerDetailsPageViewModel)this.DataContext).GetUpcommingSessions();
            //    ((SpeakerDetailsPageViewModel)this.DataContext).GetBlogsForSpeaker();
            //}
        }
Esempio n. 7
0
 public void SetItem <T>(string localStorageKey, T value)
 {
     LocalStorage.SetItem(localStorageKey, value, true);
 }
Esempio n. 8
0
        public static void Process(Context ctx)
        {
            using (IStorage file = new LocalStorage(ctx.Options.InFile, FileAccess.Read))
            {
                var nca = new Nca(ctx.Keyset, file, false);

                if (ctx.Options.HeaderOut != null)
                {
                    using (var outHeader = new FileStream(ctx.Options.HeaderOut, FileMode.Create, FileAccess.ReadWrite))
                    {
                        nca.OpenHeaderStorage().Slice(0, 0xc00).CopyToStream(outHeader);
                    }
                }

                nca.ValidateMasterHashes();
                nca.ParseNpdm();

                if (ctx.Options.BaseNca != null)
                {
                    IStorage baseFile = new LocalStorage(ctx.Options.BaseNca, FileAccess.Read);
                    var      baseNca  = new Nca(ctx.Keyset, baseFile, false);
                    nca.SetBaseNca(baseNca);
                }

                for (int i = 0; i < 3; i++)
                {
                    if (ctx.Options.SectionOut[i] != null)
                    {
                        nca.ExportSection(i, ctx.Options.SectionOut[i], ctx.Options.Raw, ctx.Options.IntegrityLevel, ctx.Logger);
                    }

                    if (ctx.Options.SectionOutDir[i] != null)
                    {
                        nca.ExtractSection(i, ctx.Options.SectionOutDir[i], ctx.Options.IntegrityLevel, ctx.Logger);
                    }

                    if (ctx.Options.Validate && nca.SectionExists(i))
                    {
                        nca.VerifySection(i, ctx.Logger);
                    }
                }

                if (ctx.Options.ListRomFs && nca.CanOpenSection(NcaSectionType.Data))
                {
                    IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, ctx.Options.IntegrityLevel);

                    foreach (DirectoryEntry entry in romfs.EnumerateEntries())
                    {
                        ctx.Logger.LogMessage(entry.FullPath);
                    }
                }

                if (ctx.Options.RomfsOutDir != null || ctx.Options.RomfsOut != null || ctx.Options.ReadBench)
                {
                    if (!nca.SectionExists(NcaSectionType.Data))
                    {
                        ctx.Logger.LogMessage("NCA has no RomFS section");
                        return;
                    }

                    if (ctx.Options.RomfsOut != null)
                    {
                        nca.ExportSection(NcaSectionType.Data, ctx.Options.RomfsOut, ctx.Options.Raw, ctx.Options.IntegrityLevel, ctx.Logger);
                    }

                    if (ctx.Options.RomfsOutDir != null)
                    {
                        nca.ExtractSection(NcaSectionType.Data, ctx.Options.RomfsOutDir, ctx.Options.IntegrityLevel, ctx.Logger);
                    }

                    if (ctx.Options.ReadBench)
                    {
                        long     bytesToRead = 1024L * 1024 * 1024 * 5;
                        IStorage storage     = nca.OpenStorage(NcaSectionType.Data, ctx.Options.IntegrityLevel);
                        var      dest        = new NullStorage(storage.GetSize());

                        int iterations = (int)(bytesToRead / storage.GetSize()) + 1;
                        ctx.Logger.LogMessage(iterations.ToString());

                        ctx.Logger.StartNewStopWatch();

                        for (int i = 0; i < iterations; i++)
                        {
                            storage.CopyTo(dest, ctx.Logger);
                            ctx.Logger.LogMessage(ctx.Logger.GetRateString());
                        }

                        ctx.Logger.PauseStopWatch();
                        ctx.Logger.LogMessage(ctx.Logger.GetRateString());
                    }
                }

                if (ctx.Options.ExefsOutDir != null || ctx.Options.ExefsOut != null)
                {
                    if (nca.Header.ContentType != ContentType.Program)
                    {
                        ctx.Logger.LogMessage("NCA's content type is not \"Program\"");
                        return;
                    }

                    if (!nca.SectionExists(NcaSectionType.Code))
                    {
                        ctx.Logger.LogMessage("Could not find an ExeFS section");
                        return;
                    }

                    if (ctx.Options.ExefsOut != null)
                    {
                        nca.ExportSection(NcaSectionType.Code, ctx.Options.ExefsOut, ctx.Options.Raw, ctx.Options.IntegrityLevel, ctx.Logger);
                    }

                    if (ctx.Options.ExefsOutDir != null)
                    {
                        nca.ExtractSection(NcaSectionType.Code, ctx.Options.ExefsOutDir, ctx.Options.IntegrityLevel, ctx.Logger);
                    }
                }

                if (ctx.Options.PlaintextOut != null)
                {
                    nca.OpenDecryptedNca().WriteAllBytes(ctx.Options.PlaintextOut, ctx.Logger);
                }

                if (!ctx.Options.ReadBench)
                {
                    ctx.Logger.LogMessage(nca.Print());
                }
            }
        }
Esempio n. 9
0
 public BaseService(HttpClient httpClient, LocalStorage localStorage, string endpoint)
 {
     _httpClient   = httpClient;
     _localStorage = localStorage;
     urlBase       = $"http://localhost/{endpoint}";
 }
Esempio n. 10
0
        private void ImportBtn_Click(object sender, RoutedEventArgs e)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            //check that we've got the relevant data needed
            if (!Data.Columns.Contains("Date") && !Data.Columns.Contains("DateTime"))
            {
                MessageBox.Show("Must have a date column.");
                return;
            }

            if ((BarSize)FrequencyComboBox.SelectedItem < BarSize.OneDay && !Data.Columns.Contains("DateTime") && !Data.Columns.Contains("Time"))
            {
                MessageBox.Show("Must have time column at this frequency");
                return;
            }

            if (!Data.Columns.Contains("Open") ||
                !Data.Columns.Contains("High") ||
                !Data.Columns.Contains("Low")  ||
                !Data.Columns.Contains("Close"))
            {
                MessageBox.Show("Must have all OHLC columns.");
                return;
            }

            //make sure the timezone is set, and get it
            if (string.IsNullOrEmpty(_instrument.Exchange.Timezone))
            {
                MessageBox.Show("Instrument's exchange has no set timezone, can't import.");
                return;
            }

            //todo make sure the user has picked the right frequency

            var tzInfo = TimeZoneInfo.FindSystemTimeZoneById(_instrument.Exchange.Timezone);

            //get the multipliers
            decimal priceMultiplier;
            int volumeMultiplier;
            bool parseWorked = decimal.TryParse(PriceMultiplier.Text, out priceMultiplier);
            if (!parseWorked) priceMultiplier = 1;
            parseWorked = int.TryParse(VolumeMultiplier.Text, out volumeMultiplier);
            if (!parseWorked) volumeMultiplier = 1;

            //lines to skip
            int toSkip;
            parseWorked = int.TryParse(StartingLine.Text, out toSkip);
            if(!parseWorked) toSkip = 1;

            //get the frequency
            var frequency = (BarSize)FrequencyComboBox.SelectedItem;

            //separator
            char[] separator = DelimiterBox.Text.ToCharArray();

            List<OHLCBar> bars = new List<OHLCBar>();

            string[] columns = new string[Data.Columns.Count];
            for (int i = 0; i < Data.Columns.Count; i++)
            {
                columns[i] = Data.Columns[i].ColumnName;
            }

            //determining time: if the freq is >= one day, then the time is simply the session end for this day
            Dictionary<int, TimeSpan> sessionEndTimes = new Dictionary<int, TimeSpan>();

            //1 day and up: we can load it all in one go with no trouble, also may require adjustment
            bool periodicSaving = frequency < BarSize.OneDay;
            OHLCBar bar;
            var barsCount = 0;
            using (StreamReader sr = new StreamReader(FilePathTextBox.Text))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    barsCount++;
                    if (barsCount < toSkip) continue;

                    try
                    {
                        bar = ParseLine(line.Split(separator), columns, priceMultiplier, volumeMultiplier);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Importing error: " + ex.Message);
                        return;
                    }

                    //only add the bar if it falls within the specified date range
                    if (bar.DT >= MinDT.Value && bar.DT <= MaxDT.Value)
                    {
                        bars.Add(bar);
                    }

                    if (periodicSaving && bars.Count > 1000)
                    {
                        //convert to exchange timezone
                        ConvertTimeZone(bars, tzInfo);

                        //low frequencies, < 1 day. No adjustment required and inserting data at intervals instead of all at once
                        using (var storage = new LocalStorage())
                        {
                            try
                            {
                                storage.AddData(bars, _instrument, frequency, OverwriteCheckbox.IsChecked.HasValue && OverwriteCheckbox.IsChecked.Value, false);
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show("Error: " + ex.Message);
                            }
                        }
                        bars.Clear();
                    }
                }
            }

            if (bars.Count == 0) return;

            //convert to exchange timezone
            ConvertTimeZone(bars, tzInfo);

            //if only the date column is set, we need to get the session info and generate the closing time ourselves
            if (frequency >= BarSize.OneDay && !Data.Columns.Contains("Time") && !Data.Columns.Contains("DateTime"))
            {
                //get the closing time for every day of the week
                var dotwValues = MyUtils.GetEnumValues<DayOfTheWeek>();

                foreach (DayOfTheWeek d in dotwValues)
                {
                    if (_instrument.Sessions.Any(x => x.ClosingDay == d && x.IsSessionEnd))
                    {
                        var endTime = _instrument.Sessions.First(x => x.ClosingDay == d && x.IsSessionEnd).ClosingTime;
                        sessionEndTimes.Add((int)d, endTime);
                    }
                    else
                    {
                        sessionEndTimes.Add((int)d, TimeSpan.FromSeconds(0));
                    }
                }

                for (int i = 0; i < bars.Count; i++)
                {
                    int dayOfWeek = bars[i].DT.DayOfWeek.ToInt();
                    bars[i].DT = bars[i].DT.Date + sessionEndTimes[dayOfWeek];
                }
            }

            //if there are no dividends/splits, but there IS an adjclose column, use that to adjust data right here
            //if there are divs/splits, adjustment will be done by the local storage
            if (frequency >= BarSize.OneDay && !Data.Columns.Contains("Dividends") && !Data.Columns.Contains("Splits") && Data.Columns.Contains("AdjClose"))
            {
                //if we have an adjusted close to work off of, we just use the ratio to get the OHL
                for (int i = 0; i < bars.Count; i++)
                {
                    if (bars[i].AdjClose == null) continue;

                    decimal ratio = bars[i].AdjClose.Value / bars[i].Close;
                    bars[i].AdjOpen = bars[i].Open * ratio;
                    bars[i].AdjHigh = bars[i].High * ratio;
                    bars[i].AdjLow = bars[i].Low * ratio;
                }
            }

            //sort by date
            if(frequency >= BarSize.OneDay)
                bars.Sort((x, y) => x.DT.CompareTo(y.DT));

            //try to import
            using (var storage = new LocalStorage())
            {
                try
                {
                    storage.AddData(bars,
                        _instrument,
                        frequency,
                        OverwriteCheckbox.IsChecked.HasValue && OverwriteCheckbox.IsChecked.Value,
                        frequency >= BarSize.OneDay);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: " + ex.Message);
                }
            }
            sw.Stop();
            MessageBox.Show(string.Format("Imported {0} bars in {1} ms.", barsCount, sw.ElapsedMilliseconds));
        }
Esempio n. 11
0
        public void EnsureInitialized(ContentManager contentManager)
        {
            if (_fontData == null)
            {
                _device.Memory.FillWithZeros(_physicalAddress, Horizon.FontSize);

                uint fontOffset = 0;

                FontInfo CreateFont(string name)
                {
                    if (contentManager.TryGetFontTitle(name, out long fontTitle) &&
                        contentManager.TryGetFontFilename(name, out string fontFilename))
                    {
                        string contentPath = contentManager.GetInstalledContentPath(fontTitle, StorageId.NandSystem, NcaContentType.Data);
                        string fontPath    = _device.FileSystem.SwitchPathToSystemPath(contentPath);

                        if (!string.IsNullOrWhiteSpace(fontPath))
                        {
                            byte[] data;

                            using (IStorage ncaFileStream = new LocalStorage(fontPath, FileAccess.Read, FileMode.Open))
                            {
                                Nca         nca   = new Nca(_device.System.KeySet, ncaFileStream);
                                IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, _device.System.FsIntegrityCheckLevel);

                                romfs.OpenFile(out IFile fontFile, "/" + fontFilename, OpenMode.Read).ThrowIfFailure();

                                data = DecryptFont(fontFile.AsStream());
                            }

                            FontInfo info = new FontInfo((int)fontOffset, data.Length);

                            WriteMagicAndSize(_physicalAddress + fontOffset, data.Length);

                            fontOffset += 8;

                            uint start = fontOffset;

                            for (; fontOffset - start < data.Length; fontOffset++)
                            {
                                _device.Memory.WriteByte(_physicalAddress + fontOffset, data[fontOffset - start]);
                            }

                            return(info);
                        }
                    }

                    string fontFilePath = Path.Combine(_fontsPath, name + ".ttf");

                    if (File.Exists(fontFilePath))
                    {
                        byte[] data = File.ReadAllBytes(fontFilePath);

                        FontInfo info = new FontInfo((int)fontOffset, data.Length);

                        WriteMagicAndSize(_physicalAddress + fontOffset, data.Length);

                        fontOffset += 8;

                        uint start = fontOffset;

                        for (; fontOffset - start < data.Length; fontOffset++)
                        {
                            _device.Memory.WriteByte(_physicalAddress + fontOffset, data[fontOffset - start]);
                        }

                        return(info);
                    }
                    else
                    {
                        throw new InvalidSystemResourceException($"Font \"{name}.ttf\" not found. Please provide it in \"{_fontsPath}\".");
                    }
                }

                _fontData = new Dictionary <SharedFontType, FontInfo>
                {
                    { SharedFontType.JapanUsEurope, CreateFont("FontStandard") },
                    { SharedFontType.SimplifiedChinese, CreateFont("FontChineseSimplified") },
                    { SharedFontType.SimplifiedChineseEx, CreateFont("FontExtendedChineseSimplified") },
                    { SharedFontType.TraditionalChinese, CreateFont("FontChineseTraditional") },
                    { SharedFontType.Korean, CreateFont("FontKorean") },
                    { SharedFontType.NintendoEx, CreateFont("FontNintendoExtended") }
                };

                if (fontOffset > Horizon.FontSize)
                {
                    throw new InvalidSystemResourceException(
                              $"The sum of all fonts size exceed the shared memory size. " +
                              $"Please make sure that the fonts don't exceed {Horizon.FontSize} bytes in total. " +
                              $"(actual size: {fontOffset} bytes).");
                }
            }
        }
Esempio n. 12
0
        internal ResultCode GetTimeZoneBinary(string locationName, out Stream timeZoneBinaryStream, out LocalStorage ncaFile)
        {
            timeZoneBinaryStream = null;
            ncaFile = null;

            if (!IsLocationNameValid(locationName))
            {
                return(ResultCode.TimeZoneNotFound);
            }

            ncaFile = new LocalStorage(_device.FileSystem.SwitchPathToSystemPath(GetTimeZoneBinaryTitleContentPath()), FileAccess.Read, FileMode.Open);

            Nca         nca   = new Nca(_device.System.KeySet, ncaFile);
            IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, _device.System.FsIntegrityCheckLevel);

            Result result = romfs.OpenFile(out IFile timeZoneBinaryFile, $"/zoneinfo/{locationName}", OpenMode.Read);

            timeZoneBinaryStream = timeZoneBinaryFile.AsStream();

            return((ResultCode)result.Value);
        }
Esempio n. 13
0
        public static void Process(Context ctx)
        {
            var accessNeeded = FileAccess.Read;

            if (ctx.Options.SignSave || ctx.Options.ReplaceFileDest != null && ctx.Options.ReplaceFileSource != null ||
                ctx.Options.RepackSource != null || ctx.Options.TrimSave)
            {
                accessNeeded = FileAccess.ReadWrite;
            }

            using (var file = new LocalStorage(ctx.Options.InFile, accessNeeded))
            {
                bool signNeeded = ctx.Options.SignSave;

                var save            = new SaveDataFileSystem(ctx.KeySet, file, ctx.Options.IntegrityLevel, true);
                FileSystemClient fs = ctx.Horizon.Fs;

                fs.Register("save".ToU8Span(), save);
                fs.Impl.EnableFileSystemAccessorAccessLog("save".ToU8Span());

                if (ctx.Options.Validate)
                {
                    save.Verify(ctx.Logger);
                }

                if (ctx.Options.OutDir != null)
                {
                    fs.Register("output".ToU8Span(), new LocalFileSystem(ctx.Options.OutDir));
                    fs.Impl.EnableFileSystemAccessorAccessLog("output".ToU8Span());

                    FsUtils.CopyDirectoryWithProgress(fs, "save:/".ToU8Span(), "output:/".ToU8Span(), logger: ctx.Logger).ThrowIfFailure();

                    fs.Unmount("output".ToU8Span());
                }

                if (ctx.Options.DebugOutDir != null)
                {
                    string dir = ctx.Options.DebugOutDir;

                    ExportSaveDebug(ctx, dir, save);
                }

                try
                {
                    if (ctx.Options.ReplaceFileDest != null && ctx.Options.ReplaceFileSource != null)
                    {
                        string destFilename = ctx.Options.ReplaceFileDest;
                        if (!destFilename.StartsWith("/"))
                        {
                            destFilename = '/' + destFilename;
                        }

                        using (IFile inFile = new LocalFile(ctx.Options.ReplaceFileSource, OpenMode.Read))
                        {
                            save.OpenFile(out IFile outFile, destFilename.ToU8String(), OpenMode.ReadWrite).ThrowIfFailure();

                            using (outFile)
                            {
                                inFile.GetSize(out long inFileSize).ThrowIfFailure();
                                outFile.GetSize(out long outFileSize).ThrowIfFailure();

                                if (inFileSize != outFileSize)
                                {
                                    outFile.SetSize(inFileSize).ThrowIfFailure();
                                }

                                inFile.CopyTo(outFile, ctx.Logger);

                                ctx.Logger.LogMessage($"Replaced file {destFilename}");
                            }
                        }

                        signNeeded = true;
                    }

                    if (ctx.Options.RepackSource != null)
                    {
                        fs.Register("input".ToU8Span(), new LocalFileSystem(ctx.Options.RepackSource));
                        fs.Impl.EnableFileSystemAccessorAccessLog("input".ToU8Span());

                        fs.CleanDirectoryRecursively("save:/".ToU8Span());
                        fs.Commit("save".ToU8Span());

                        FsUtils.CopyDirectoryWithProgress(fs, "input:/".ToU8Span(), "save:/".ToU8Span(), logger: ctx.Logger).ThrowIfFailure();

                        fs.Commit("save".ToU8Span());
                        fs.Unmount("input".ToU8Span());

                        signNeeded = true;
                    }
                }
                finally
                {
                    if (signNeeded)
                    {
                        if (save.Commit(ctx.KeySet).IsSuccess())
                        {
                            ctx.Logger.LogMessage(
                                $"Successfully signed save file with key {ctx.KeySet.DeviceUniqueSaveMacKeys[0].ToString()}");
                        }
                        else
                        {
                            ctx.Logger.LogMessage("Unable to sign save file. Do you have all the required keys?");
                        }

                        signNeeded = false;
                    }
                }

                if (ctx.Options.TrimSave)
                {
                    save.FsTrim();
                    signNeeded = true;
                    ctx.Logger.LogMessage("Trimmed save file");
                }

                if (signNeeded)
                {
                    if (save.Commit(ctx.KeySet).IsSuccess())
                    {
                        ctx.Logger.LogMessage(
                            $"Successfully signed save file with key {ctx.KeySet.DeviceUniqueSaveMacKeys[0].ToString()}");
                    }
                    else
                    {
                        ctx.Logger.LogMessage("Unable to sign save file. Do you have all the required keys?");
                    }

                    fs.Unmount("save".ToU8Span());
                    return;
                }

                if (ctx.Options.ListFiles)
                {
                    foreach (DirectoryEntryEx entry in save.EnumerateEntries())
                    {
                        ctx.Logger.LogMessage(entry.FullPath);
                    }
                }

                ctx.Logger.LogMessage(save.Print(ctx.KeySet));
                //ctx.Logger.LogMessage(PrintFatLayout(save.SaveDataFileSystemCore));

                fs.Unmount("save".ToU8Span());
            }
        }
Esempio n. 14
0
        private async Task <DriveFileList> GetDriveFileList()
        {
            string folderId = await LocalStorage.GetItemAsync <string>(Constants.KeyName_DriveFolderId);

            return(await GoogleDriveApi.GetDriveFileList(folderId));
        }
Esempio n. 15
0
 public LoginService(HttpClient http, LocalStorage localStorage) => (_http, _localStorage) = (http, localStorage);
        private int GetProductCount()
        {
            var cart = LocalStorage.GetItem <List <ProductVariant> >("cart");

            return(cart != null ? cart.Count : 0);
        }
Esempio n. 17
0
        public static void Process(Context ctx)
        {
            using (var file = new LocalStorage(ctx.Options.InFile, FileAccess.Read))
            {
                var xci = new Xci(ctx.Keyset, file);

                ctx.Logger.LogMessage(xci.Print());

                if (ctx.Options.RootDir != null)
                {
                    xci.OpenPartition(XciPartitionType.Root).Extract(ctx.Options.RootDir, ctx.Logger);
                }

                if (ctx.Options.UpdateDir != null && xci.HasPartition(XciPartitionType.Update))
                {
                    xci.OpenPartition(XciPartitionType.Update).Extract(ctx.Options.UpdateDir, ctx.Logger);
                }

                if (ctx.Options.NormalDir != null && xci.HasPartition(XciPartitionType.Normal))
                {
                    xci.OpenPartition(XciPartitionType.Normal).Extract(ctx.Options.NormalDir, ctx.Logger);
                }

                if (ctx.Options.SecureDir != null && xci.HasPartition(XciPartitionType.Secure))
                {
                    xci.OpenPartition(XciPartitionType.Secure).Extract(ctx.Options.SecureDir, ctx.Logger);
                }

                if (ctx.Options.LogoDir != null && xci.HasPartition(XciPartitionType.Logo))
                {
                    xci.OpenPartition(XciPartitionType.Logo).Extract(ctx.Options.LogoDir, ctx.Logger);
                }

                if (ctx.Options.OutDir != null)
                {
                    XciPartition root = xci.OpenPartition(XciPartitionType.Root);
                    if (root == null)
                    {
                        ctx.Logger.LogMessage("Could not find root partition");
                        return;
                    }

                    foreach (PartitionFileEntry sub in root.Files)
                    {
                        var    subPfs = new PartitionFileSystem(root.OpenFile(sub, OpenMode.Read).AsStorage());
                        string subDir = Path.Combine(ctx.Options.OutDir, sub.Name);

                        subPfs.Extract(subDir, ctx.Logger);
                    }
                }

                if (ctx.Options.ExefsOutDir != null || ctx.Options.ExefsOut != null)
                {
                    Nca mainNca = GetXciMainNca(xci, ctx);

                    if (mainNca == null)
                    {
                        ctx.Logger.LogMessage("Could not find Program NCA");
                        return;
                    }

                    if (!mainNca.SectionExists(NcaSectionType.Code))
                    {
                        ctx.Logger.LogMessage("NCA has no ExeFS section");
                        return;
                    }

                    if (ctx.Options.ExefsOutDir != null)
                    {
                        mainNca.ExtractSection(NcaSectionType.Code, ctx.Options.ExefsOutDir, ctx.Options.IntegrityLevel, ctx.Logger);
                    }

                    if (ctx.Options.ExefsOut != null)
                    {
                        mainNca.ExportSection(NcaSectionType.Code, ctx.Options.ExefsOut, ctx.Options.Raw, ctx.Options.IntegrityLevel, ctx.Logger);
                    }
                }

                if (ctx.Options.RomfsOutDir != null || ctx.Options.RomfsOut != null)
                {
                    Nca mainNca = GetXciMainNca(xci, ctx);

                    if (mainNca == null)
                    {
                        ctx.Logger.LogMessage("Could not find Program NCA");
                        return;
                    }

                    if (!mainNca.SectionExists(NcaSectionType.Data))
                    {
                        ctx.Logger.LogMessage("NCA has no RomFS section");
                        return;
                    }

                    ProcessRomfs.Process(ctx, mainNca.OpenStorage(NcaSectionType.Data, ctx.Options.IntegrityLevel, false));
                }
            }
        }
Esempio n. 18
0
 public string GetItem(string localStorageKey, string defaultValue)
 {
     return(LocalStorage.GetItem <string>(localStorageKey, defaultValue, false));
 }
Esempio n. 19
0
        // Creates IL locals for accessing closures
        private void EmitClosureAccess(LambdaCompiler lc, HoistedLocals locals)
        {
            if (locals == null)
            {
                return;
            }

            EmitClosureToVariable(lc, locals);

            while ((locals = locals.Parent) != null)
            {
                ParameterExpression v = locals.SelfVariable;
                var local = new LocalStorage(lc, v);
                local.EmitStore(ResolveVariable(v));
                _locals.Add(v, local);
            }
        }
Esempio n. 20
0
 public JwtDecode(LocalStorage localStorage)
 {
     _localStorage = localStorage;
 }
Esempio n. 21
0
 public void SetItem(string localStorageKey, bool value)
 {
     LocalStorage.SetItem(localStorageKey, value, false);
 }
        public static bool ValidSession(string controller)
        {
            bool response = false;

            try
            {
                bool   tokenExists = false;
                string role        = string.Empty;

                using (var storage = new LocalStorage())
                {
                    tokenExists = storage.Exists(StorageType.Token.ToString());
                }
                using (var storage = new LocalStorage())
                {
                    role = storage.Get(StorageType.Role.ToString()).ToString();
                }
                if (role == "Admin")
                {
                    if (tokenExists &&
                        (controller == "Dashboard" ||
                         controller == "Profile" ||
                         controller == "Company" ||
                         controller == "Shop" ||
                         controller == "User" ||
                         controller == "Template" ||
                         controller == "Balance"))
                    {
                        response = true;
                    }
                    else
                    {
                        response = false;
                    }
                }
                else if (role == "Company")
                {
                    if (tokenExists &&
                        (controller == "Dashboard" ||
                         controller == "Profile" ||
                         controller == "Shop" ||
                         controller == "User" ||
                         controller == "Balance" ||
                         controller == "Card" ||
                         controller == "Code"))
                    {
                        response = true;
                    }
                    else
                    {
                        response = false;
                    }
                }
                else if (role == "Shop")
                {
                    if (tokenExists &&
                        (controller == "Sale" ||
                         controller == "Profile"))
                    {
                        response = true;
                    }
                    else
                    {
                        response = false;
                    }
                }
            }
            catch (Exception ex)
            {
                response = false;
            }
            return(response);
        }
Esempio n. 23
0
        private void LoadDataBtn_Click(object sender, RoutedEventArgs e)
        {
            Data.Clear();

            //grab the data
            using (var localStorage = new LocalStorage())
            {
                var tzInfo = TimeZoneInfo.FindSystemTimeZoneById(TheInstrument.Exchange.Timezone);
                var bars = localStorage.GetData(TheInstrument, StartTime, EndTime, (BarSize)ResolutionComboBox.SelectedItem);
                foreach (OHLCBar b in bars)
                {
                    //do any required time zone coversions
                    if (TimezoneComboBox.Text == "UTC")
                    {
                        b.DT = TimeZoneInfo.ConvertTimeToUtc(b.DT, tzInfo);
                    }
                    else if (TimezoneComboBox.Text == "Local")
                    {
                        b.DT = TimeZoneInfo.ConvertTime(b.DT, TimeZoneInfo.Local, tzInfo);
                    }
                    Data.Add(b);
                }
                _loadedFrequency = (BarSize)ResolutionComboBox.SelectedItem;
            }

            StatusLabel.Content = string.Format("Loaded {0} Bars", Data.Count);
        }
Esempio n. 24
0
 public AuthService(HttpClient http, LocalStorage localStorage)
 {
     _http         = http;
     _localStorage = localStorage;
 }
Esempio n. 25
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="httpClient">Http client</param>
 public HttpMessageService(HttpClient httpClient, LocalStorage storage)
 {
     _httpClient = httpClient;
     _storage    = storage;
 }
Esempio n. 26
0
        public void LoadKip(string kipPath)
        {
            using IStorage kipFile = new LocalStorage(kipPath, FileAccess.Read);

            ProgramLoader.LoadKip(KernelContext, new KipExecutable(kipFile));
        }
Esempio n. 27
0
 /// <summary>
 ///
 /// </summary>
 public AuthenticationService(LocalStorage localStorage, ILogger <AuthenticationService> logger)
 {
     _localStorage = localStorage;
     _logger       = logger;
 }
Esempio n. 28
0
        //delete data from selected instruments
        private void ClearDataBtn_ItemClick(object sender, RoutedEventArgs routedEventArgs)
        {
            var selectedInstruments = InstrumentsGrid.SelectedItems;
            if (selectedInstruments.Count == 0) return;

            if (selectedInstruments.Count == 1)
            {
                var inst = (Instrument)selectedInstruments[0];
                MessageBoxResult res = MessageBox.Show(string.Format("Are you sure you want to delete all data from {0} @ {1}?", inst.Symbol, inst.Datasource.Name),
                    "Delete", MessageBoxButton.YesNo);
                if (res == MessageBoxResult.No) return;
            }
            else
            {
                MessageBoxResult res = MessageBox.Show(string.Format("Are you sure you want to delete all data from {0} instruments?", selectedInstruments.Count),
                    "Delete", MessageBoxButton.YesNo);
                if (res == MessageBoxResult.No) return;
            }

            using (var storage = new LocalStorage())
            {
                foreach (Instrument i in selectedInstruments)
                {
                    try
                    {
                        storage.DeleteAllInstrumentData(i);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }

            StatusBarLabel.Content = "Instrument data deleted";
        }
Esempio n. 29
0
        void CreateLocalStorage(Jint.Engine engine)
        {
            var storage = new LocalStorage();

            engine.SetValue("localStorage", storage);
        }
Esempio n. 30
0
        //check the latest date we have available in local storage, then request historical data from that date to the current time
        void UpdateHistoricalDataBtn_ItemClick(object sender, RoutedEventArgs routedEventArgs)
        {
            var frequency = (BarSize)((MenuItem)sender).Tag;
            List<Instrument> selectedInstruments = InstrumentsGrid.SelectedItems.Cast<Instrument>().ToList();

            int requestCount = 0;

            using (var localStorage = new LocalStorage())
            {
                foreach (Instrument i in selectedInstruments)
                {
                    if (!i.ID.HasValue) continue;

                    var storageInfo = localStorage.GetStorageInfo(i.ID.Value);
                    if (storageInfo.Any(x => x.Frequency == frequency))
                    {
                        var relevantStorageInfo = storageInfo.First(x => x.Frequency == frequency);
                        _client.RequestHistoricalData(new HistoricalDataRequest(
                            i,
                            frequency,
                            relevantStorageInfo.LatestDate + frequency.ToTimeSpan(),
                            DateTime.Now,
                            true,
                            false,
                            true));
                        requestCount++;
                    }
                }
            }

            if (_progressBar.Value >= _progressBar.Maximum)
            {
                _progressBar.Maximum = requestCount;
                _progressBar.Value = 0;
            }
            else
            {
                _progressBar.Maximum += requestCount;
            }
        }
Esempio n. 31
0
        // OpenDataStorageByDataId(u8 storageId, nn::ApplicationId tid) -> object<nn::fssrv::sf::IStorage> dataStorage
        public ResultCode OpenDataStorageByDataId(ServiceCtx context)
        {
            StorageId storageId = (StorageId)context.RequestData.ReadByte();

            byte[] padding = context.RequestData.ReadBytes(7);
            long   titleId = context.RequestData.ReadInt64();

            // We do a mitm here to find if the request is for an AOC.
            // This is because AOC can be distributed over multiple containers in the emulator.
            if (context.Device.System.ContentManager.GetAocDataStorage((ulong)titleId, out LibHac.Fs.IStorage aocStorage))
            {
                Logger.PrintInfo(LogClass.Loader, $"Opened AddOnContent Data TitleID={titleId:X16}");

                MakeObject(context, new FileSystemProxy.IStorage(aocStorage));

                return(ResultCode.Success);
            }

            NcaContentType contentType = NcaContentType.Data;

            StorageId installedStorage = context.Device.System.ContentManager.GetInstalledStorage(titleId, contentType, storageId);

            if (installedStorage == StorageId.None)
            {
                contentType = NcaContentType.PublicData;

                installedStorage = context.Device.System.ContentManager.GetInstalledStorage(titleId, contentType, storageId);
            }

            if (installedStorage != StorageId.None)
            {
                string contentPath = context.Device.System.ContentManager.GetInstalledContentPath(titleId, storageId, contentType);
                string installPath = context.Device.FileSystem.SwitchPathToSystemPath(contentPath);

                if (!string.IsNullOrWhiteSpace(installPath))
                {
                    string ncaPath = installPath;

                    if (File.Exists(ncaPath))
                    {
                        try
                        {
                            LibHac.Fs.IStorage ncaStorage = new LocalStorage(ncaPath, FileAccess.Read, FileMode.Open);
                            Nca nca = new Nca(context.Device.System.KeySet, ncaStorage);
                            LibHac.Fs.IStorage romfsStorage = nca.OpenStorage(NcaSectionType.Data, context.Device.System.FsIntegrityCheckLevel);

                            MakeObject(context, new FileSystemProxy.IStorage(romfsStorage));
                        }
                        catch (HorizonResultException ex)
                        {
                            return((ResultCode)ex.ResultValue.Value);
                        }

                        return(ResultCode.Success);
                    }
                    else
                    {
                        throw new FileNotFoundException($"No Nca found in Path `{ncaPath}`.");
                    }
                }
                else
                {
                    throw new DirectoryNotFoundException($"Path for title id {titleId:x16} on Storage {storageId} was not found in Path {installPath}.");
                }
            }

            throw new FileNotFoundException($"System archive with titleid {titleId:x16} was not found on Storage {storageId}. Found in {installedStorage}.");
        }
Esempio n. 32
0
 public T GetItem <T>(string localStorageKey, T defaultValue)
 {
     return(LocalStorage.GetItem(localStorageKey, defaultValue, true));
 }
Esempio n. 33
0
 public GameStorage(LocalStorage localStorage)
 {
     _storage = localStorage;
 }
Esempio n. 34
0
 public LocalStorageDemoController(LocalStorage localStorage)
 {
     this.localStorage = localStorage;
 }
Esempio n. 35
0
        //delete one or more instruments
        private void DeleteInstrumentBtn_ItemClick(object sender, RoutedEventArgs routedEventArgs)
        {
            using (var entityContext = new MyDBContext())
            {
                var selectedInstruments = InstrumentsGrid.SelectedItems;
                if (selectedInstruments.Count == 0) return;

                if (selectedInstruments.Count == 1)
                {
                    var inst = (Instrument)selectedInstruments[0];
                    MessageBoxResult res = MessageBox.Show(string.Format("Are you sure you want to delete {0} @ {1}?", inst.Symbol, inst.Datasource.Name),
                        "Delete", MessageBoxButton.YesNo);
                    if (res == MessageBoxResult.No) return;
                }
                else
                {
                    MessageBoxResult res = MessageBox.Show(string.Format("Are you sure you want to delete {0} instruments?", selectedInstruments.Count),
                        "Delete", MessageBoxButton.YesNo);
                    if (res == MessageBoxResult.No) return;
                }

                List<Instrument> toRemove = new List<Instrument>();

                foreach (Instrument i in InstrumentsGrid.SelectedItems)
                {
                    entityContext.Instruments.Attach(i);
                    entityContext.Instruments.Remove(i);
                    toRemove.Add(i);
                }

                using (var localStorage = new LocalStorage())
                {
                    localStorage.Connect();

                    while (toRemove.Count > 0)
                    {
                        Instruments.Remove(toRemove[toRemove.Count - 1]);
                        localStorage.DeleteAllInstrumentData(toRemove[toRemove.Count - 1]);
                        toRemove.RemoveAt(toRemove.Count - 1);
                    }
                }

                entityContext.SaveChanges();
            }
        }
Esempio n. 36
0
 public HttpService(HttpClient _http, LocalStorage _localStorage)
 {
     http         = _http;
     localStorage = _localStorage;
     // SetAuthorizationHeader();
 }
Esempio n. 37
0
        void Start(string keys, string fwPath, bool noExfat, bool verbose, bool showNcaIndex, bool fixHashes, bool noAutoRcm, bool mariko)
        {
            Config.keyset      = ExternalKeyReader.ReadKeyFile(keys);
            Config.fwPath      = fwPath;
            Config.noExfat     = noExfat;
            Config.normalBisId = (noExfat) ? "0100000000000819" : "010000000000081B";
            Config.safeBisId   = (noExfat) ? "010000000000081A" : "010000000000081C";
            Config.verbose     = verbose;
            Config.fixHashes   = fixHashes;
            Config.noAutoRcm   = mariko || noAutoRcm;
            Config.marikoBoot  = mariko;

            int convertCount = 0;

            foreach (var foldername in Directory.GetDirectories(fwPath, "*.nca"))
            {
                convertCount++;
                File.Move($"{foldername}/00", $"{fwPath}/temp");
                Directory.Delete(foldername);
                File.Move($"{fwPath}/temp", foldername);
            }

            if (convertCount > 0)
            {
                Console.WriteLine($"Converted folder ncas to files (count: {convertCount})");
            }

            Console.WriteLine("Indexing nca files...");

            NcaIndexer ncaIndex = new NcaIndexer();

            VersionExtractor versionExtractor = new VersionExtractor(ncaIndex.FindNca("0100000000000809", NcaContentType.Meta));

            Config.v5 = versionExtractor.UseV5Save();

            string prefix     = (Config.marikoBoot) ? "a" : "NX";
            string destFolder = $"{prefix}-{versionExtractor.Version}";

            if (!noExfat)
            {
                destFolder += "_exFAT";
            }

            if (showNcaIndex)
            {
                ShowNcaIndex(ref ncaIndex, destFolder);
                return;
            }

            string saveVersion = (Config.v5) ? "v5" : "v4";

            Console.WriteLine("\nEmmcHaccGen will now generate firmware files using the following settings:\n" +
                              $"fw: {versionExtractor.Version}\n" +
                              $"Exfat Support: {!noExfat}\n" +
                              $"Key path: {keys}\n" +
                              $"Destination folder: {destFolder}\n" +
                              $"Mariko boot generation: {mariko}\n" +
                              $"Save version: {saveVersion}\n" +
                              $"AutoRCM: {!Config.noAutoRcm}\n");

            if (verbose)
            {
                Console.WriteLine($"BisIds:\nNormal: {Config.normalBisId}\nSafe:   {Config.safeBisId}\n");
            }

            // Folder creation
            Console.WriteLine("\nCreating folders..");

            if (Directory.Exists(destFolder))
            {
                Console.Write("Destination folder already exists. Delete the old folder?\nY/N: ");
                string input = Console.ReadLine();

                if (input[0].ToString().ToLower() != "y")
                {
                    return;
                }

                Console.WriteLine($"Deleting {destFolder}");
                Directory.Delete(destFolder, true);
            }

            foreach (string folder in FOLDERSTRUCTURE)
            {
                Directory.CreateDirectory($"{destFolder}{folder}");
            }

            // Bis creation
            Console.WriteLine("\nGenerating bis..");
            BisAssembler     bisAssembler     = new BisAssembler(ref ncaIndex, destFolder);
            BisFileAssembler bisFileAssembler = new BisFileAssembler($"{versionExtractor.Version}{((!noExfat) ? "_exFAT" : "")}", ref bisAssembler, $"{destFolder}/boot.bis");

            // Copy fw files
            Console.WriteLine("\nCopying files...");
            foreach (var file in Directory.EnumerateFiles(fwPath))
            {
                File.Copy(file, $"{destFolder}/SYSTEM/Contents/registered/{file.Split(new char[] { '/', '\\' }).Last().Replace(".cnmt.nca ", ".nca ")}", true);
            }

            // Archive bit setting
            Console.WriteLine("\nSetting archive bits..");
            SetArchiveRecursively($"{destFolder}/SYSTEM");
            SetArchiveRecursively($"{destFolder}/USER");

            //Imkv generation
            Console.WriteLine("\nGenerating imkvdb..");
            Imkv imkvdb = new Imkv(ref ncaIndex);

            if (verbose)
            {
                imkvdb.DumpToFile($"{destFolder}/data.arc");
            }

            File.Copy($"save.stub.{saveVersion}", $"{destFolder}/SYSTEM/save/8000000000000120", true);

            using (IStorage outfile = new LocalStorage($"{destFolder}/SYSTEM/save/8000000000000120", FileAccess.ReadWrite))
            {
                var save = new SaveDataFileSystem(Config.keyset, outfile, IntegrityCheckLevel.ErrorOnInvalid, true);
                save.OpenFile(out IFile file, new U8Span("/meta/imkvdb.arc"), OpenMode.AllowAppend | OpenMode.ReadWrite);
                using (file)
                {
                    file.Write(0, imkvdb.bytes.ToArray(), WriteOption.Flush).ThrowIfFailure();
                }
                save.Commit(Config.keyset).ThrowIfFailure();
            }
            Console.WriteLine($"Wrote save with an imvkdb size of 0x{imkvdb.bytes.Count:X4}");
        }
Esempio n. 38
0
 public ServiceOfTheme(LocalStorage localStorage)
 {
     this.localStorage = localStorage;
 }
Esempio n. 39
0
 // Allocates slots for IL locals or IL arguments
 private void AllocateLocals(LambdaCompiler lc) {
     foreach (ParameterExpression v in GetVariables()) {
         if (Definitions[v] == VariableStorageKind.Local) {
             Storage s;
             //If v is in lc.Parameters, it is a parameter.
             //Otherwise, it is a local variable.
             if (lc.Parameters.Contains(v)) {
                 s = new ArgumentStorage(lc, v);
             } else {
                 s = new LocalStorage(lc, v);
             }
             _locals.Add(v, s);
         }
     }
 }
Esempio n. 40
0
        public static void Process(Context ctx)
        {
            using (IStorage file = new LocalStorage(ctx.Options.InFile, FileAccess.Read))
            {
                var nca     = new Nca(ctx.Keyset, file);
                Nca baseNca = null;

                var ncaHolder = new NcaHolder {
                    Nca = nca
                };

                if (ctx.Options.HeaderOut != null)
                {
                    using (var outHeader = new FileStream(ctx.Options.HeaderOut, FileMode.Create, FileAccess.ReadWrite))
                    {
                        nca.OpenDecryptedHeaderStorage().Slice(0, 0xc00).CopyToStream(outHeader);
                    }
                }

                if (ctx.Options.BaseNca != null)
                {
                    IStorage baseFile = new LocalStorage(ctx.Options.BaseNca, FileAccess.Read);
                    baseNca = new Nca(ctx.Keyset, baseFile);
                }

                for (int i = 0; i < 3; i++)
                {
                    if (ctx.Options.SectionOut[i] != null)
                    {
                        OpenStorage(i).WriteAllBytes(ctx.Options.SectionOut[i], ctx.Logger);
                    }

                    if (ctx.Options.SectionOutDir[i] != null)
                    {
                        FileSystemClient fs = ctx.Horizon.Fs;

                        string mountName = $"section{i}";

                        fs.Register(mountName.ToU8Span(), OpenFileSystem(i));
                        fs.Register("output".ToU8Span(), new LocalFileSystem(ctx.Options.SectionOutDir[i]));

                        FsUtils.CopyDirectoryWithProgress(fs, mountName + ":/", "output:/", logger: ctx.Logger);

                        fs.Unmount(mountName);
                        fs.Unmount("output");
                    }

                    if (ctx.Options.Validate && nca.SectionExists(i))
                    {
                        if (nca.Header.GetFsHeader(i).IsPatchSection() && baseNca != null)
                        {
                            ncaHolder.Validities[i] = baseNca.VerifySection(nca, i, ctx.Logger);
                        }
                        else
                        {
                            ncaHolder.Validities[i] = nca.VerifySection(i, ctx.Logger);
                        }
                    }
                }

                if (ctx.Options.ListRomFs && nca.CanOpenSection(NcaSectionType.Data))
                {
                    IFileSystem romfs = OpenFileSystemByType(NcaSectionType.Data);

                    foreach (DirectoryEntryEx entry in romfs.EnumerateEntries())
                    {
                        ctx.Logger.LogMessage(entry.FullPath);
                    }
                }

                if (ctx.Options.RomfsOutDir != null || ctx.Options.RomfsOut != null || ctx.Options.ReadBench)
                {
                    if (!nca.SectionExists(NcaSectionType.Data))
                    {
                        ctx.Logger.LogMessage("NCA has no RomFS section");
                        return;
                    }

                    if (ctx.Options.RomfsOut != null)
                    {
                        OpenStorageByType(NcaSectionType.Data).WriteAllBytes(ctx.Options.RomfsOut, ctx.Logger);
                    }

                    if (ctx.Options.RomfsOutDir != null)
                    {
                        FileSystemClient fs = ctx.Horizon.Fs;

                        fs.Register("rom".ToU8Span(), OpenFileSystemByType(NcaSectionType.Data));
                        fs.Register("output".ToU8Span(), new LocalFileSystem(ctx.Options.RomfsOutDir));

                        FsUtils.CopyDirectoryWithProgress(fs, "rom:/", "output:/", logger: ctx.Logger);

                        fs.Unmount("rom");
                        fs.Unmount("output");
                    }

                    if (ctx.Options.ReadBench)
                    {
                        long     bytesToRead = 1024L * 1024 * 1024 * 5;
                        IStorage storage     = OpenStorageByType(NcaSectionType.Data);

                        storage.GetSize(out long sectionSize).ThrowIfFailure();

                        var dest = new NullStorage(sectionSize);

                        int iterations = (int)(bytesToRead / sectionSize) + 1;
                        ctx.Logger.LogMessage(iterations.ToString());

                        ctx.Logger.StartNewStopWatch();

                        for (int i = 0; i < iterations; i++)
                        {
                            storage.CopyTo(dest, ctx.Logger);
                            ctx.Logger.LogMessage(ctx.Logger.GetRateString());
                        }

                        ctx.Logger.PauseStopWatch();
                        ctx.Logger.LogMessage(ctx.Logger.GetRateString());
                    }
                }

                if (ctx.Options.ExefsOutDir != null || ctx.Options.ExefsOut != null)
                {
                    if (nca.Header.ContentType != NcaContentType.Program)
                    {
                        ctx.Logger.LogMessage("NCA's content type is not \"Program\"");
                        return;
                    }

                    if (!nca.SectionExists(NcaSectionType.Code))
                    {
                        ctx.Logger.LogMessage("Could not find an ExeFS section");
                        return;
                    }

                    if (ctx.Options.ExefsOut != null)
                    {
                        OpenStorageByType(NcaSectionType.Code).WriteAllBytes(ctx.Options.ExefsOut, ctx.Logger);
                    }

                    if (ctx.Options.ExefsOutDir != null)
                    {
                        FileSystemClient fs = ctx.Horizon.Fs;

                        fs.Register("code".ToU8Span(), OpenFileSystemByType(NcaSectionType.Code));
                        fs.Register("output".ToU8Span(), new LocalFileSystem(ctx.Options.ExefsOutDir));

                        FsUtils.CopyDirectoryWithProgress(fs, "code:/", "output:/", logger: ctx.Logger);

                        fs.Unmount("code");
                        fs.Unmount("output");
                    }
                }

                if (ctx.Options.PlaintextOut != null)
                {
                    nca.OpenDecryptedNca().WriteAllBytes(ctx.Options.PlaintextOut, ctx.Logger);
                }

                if (!ctx.Options.ReadBench)
                {
                    ctx.Logger.LogMessage(ncaHolder.Print());
                }

                IStorage OpenStorage(int index)
                {
                    if (ctx.Options.Raw)
                    {
                        if (baseNca != null)
                        {
                            return(baseNca.OpenRawStorageWithPatch(nca, index));
                        }

                        return(nca.OpenRawStorage(index));
                    }

                    if (baseNca != null)
                    {
                        return(baseNca.OpenStorageWithPatch(nca, index, ctx.Options.IntegrityLevel));
                    }

                    return(nca.OpenStorage(index, ctx.Options.IntegrityLevel));
                }

                IFileSystem OpenFileSystem(int index)
                {
                    if (baseNca != null)
                    {
                        return(baseNca.OpenFileSystemWithPatch(nca, index, ctx.Options.IntegrityLevel));
                    }

                    return(nca.OpenFileSystem(index, ctx.Options.IntegrityLevel));
                }

                IStorage OpenStorageByType(NcaSectionType type)
                {
                    return(OpenStorage(Nca.GetSectionIndexFromType(type, nca.Header.ContentType)));
                }

                IFileSystem OpenFileSystemByType(NcaSectionType type)
                {
                    return(OpenFileSystem(Nca.GetSectionIndexFromType(type, nca.Header.ContentType)));
                }
            }
        }
Esempio n. 41
0
 // Allocates slots for IL locals or IL arguments
 private void AllocateLocals(LambdaCompiler lc)
 {
     foreach (ParameterExpression v in GetVariables())
     {
         if (Definitions[v] == VariableStorageKind.Local)
         {
             //
             // If v is in lc.Parameters, it is a parameter.
             // Otherwise, it is a local variable.
             //
             // Also, for inlined lambdas we'll create a local, which
             // is possibly a byref local if the parameter is byref.
             //
             Storage s;
             if (IsMethod && lc.Parameters.Contains(v))
             {
                 s = new ArgumentStorage(lc, v);
             }
             else
             {
                 s = new LocalStorage(lc, v);
             }
             _locals.Add(v, s);
         }
     }
 }
Esempio n. 42
0
 public RepositorEntrant(LocalStorage storage)
 {
     db = storage;
 }
 private void EmitClosureAccess(LambdaCompiler lc, HoistedLocals locals)
 {
     if (locals != null)
     {
         this.EmitClosureToVariable(lc, locals);
         while ((locals = locals.Parent) != null)
         {
             ParameterExpression selfVariable = locals.SelfVariable;
             LocalStorage storage = new LocalStorage(lc, selfVariable);
             storage.EmitStore(this.ResolveVariable(selfVariable));
             this._locals.Add(selfVariable, storage);
         }
     }
 }
Esempio n. 44
0
        public static void AddAuthorizationHeader(HttpClient client)
        {
            var token = LocalStorage.GetToken();

            client.DefaultRequestHeaders.Add("Authorization", $"Bearer {token}");
        }
Esempio n. 45
0
    public void Start()
    {
        switch (traceFormat) {
        case "json":
            this.traceFormatter = new SimpleJsonFormat ();
            break;
        case "xapi":
            this.traceFormatter = new XApiFormat ();
            break;
        default:
            this.traceFormatter = new DefaultTraceFromat ();
            break;
        }
        filePath = GeneratePath ();
        switch (storageType) {
        case "net":
            filePath += "Pending";
            mainStorage = new NetStorage (this, host, trackingCode);
            mainStorage.SetTracker (this);
            backupStorage = new LocalStorage (filePath);
            backupStorage.SetTracker (this);
            break;
        default:
            mainStorage = new LocalStorage (filePath);
            mainStorage.SetTracker (this);
            break;
        }

        this.startListener.SetTraceFormatter (this.traceFormatter);
        this.Connect ();
        this.nextFlush = flushInterval;

        UnityEngine.Object.DontDestroyOnLoad (this);
    }
Esempio n. 46
0
        private void DeleteBtn_Click(object sender, RoutedEventArgs e)
        {
            //get the selected bars
            var rows = DataGrid.SelectedItems;
            if (rows.Count < 0) return;

            var result = MessageBox.Show(string.Format("Are you sure you want to delete {0} rows?", rows.Count), "Delete Rows", MessageBoxButton.YesNo);
            if (result == MessageBoxResult.No) return;

            var toDelete = rows.Cast<OHLCBar>().ToList();

            using (var localStorage = new LocalStorage())
            {
                localStorage.DeleteData(TheInstrument, _loadedFrequency, toDelete);
            }

            foreach (OHLCBar bar in toDelete)
            {
                Data.Remove(bar);
            }
        }