Esempio n. 1
0
 public void initialize() {
    session = new session();
    user = new user();
    user.email = "*****@*****.**";
    user.password = "******";
    user.age = 33;
 }
Esempio n. 2
0
 public Process()
 {
     MashSteps = new List<MashStep>();
     Strike = new strike();
     Sparge = new sparge();
     Boil = new boil();
     Fermentation = new fermentation();
     Session = new session();
 }
Esempio n. 3
0
 [TestMethod] public void share_connection() {
    var email = user.email;
    var session = new session().open_connection();
       session.insert(user);
       user = session
          .param("@email", email)
          .one<user>("where email=@email");
    session.close_connection();
    assert(user.email == email);
 }
Esempio n. 4
0
        /// <summary>
        /// Download a movie asynchronously
        /// </summary>
        /// <param name="movie">The movie to download</param>
        /// <param name="downloadProgress">Report download progress</param>
        /// <param name="downloadRate">Report download rate</param>
        /// <param name="ct">Cancellation token</param>
        private async Task DownloadMovieAsync(MovieFull movie, IProgress<double> downloadProgress,
            IProgress<double> downloadRate,
            CancellationTokenSource ct)
        {
            await Task.Run(async () =>
            {
                using (var session = new session())
                {
                    Logger.Info(
                        $"Start downloading movie : {movie.Title}");

                    IsDownloadingMovie = true;

                    downloadProgress?.Report(0d);
                    downloadRate?.Report(0d);

                    session.listen_on(6881, 6889);
                    var torrentUrl = movie.WatchInFullHdQuality
                        ? movie.Torrents?.FirstOrDefault(torrent => torrent.Quality == "1080p")?.Url
                        : movie.Torrents?.FirstOrDefault(torrent => torrent.Quality == "720p")?.Url;

                    var result =
                        await
                            DownloadFileHelper.DownloadFileTaskAsync(torrentUrl,
                                Constants.TorrentDownloads + movie.ImdbCode + ".torrent", ct: ct);
                    var torrentPath = string.Empty;
                    if (result.Item3 == null && !string.IsNullOrEmpty(result.Item2))
                        torrentPath = result.Item2;

                    var addParams = new add_torrent_params
                    {
                        save_path = Constants.MovieDownloads,
                        ti = new torrent_info(torrentPath)
                    };

                    var handle = session.add_torrent(addParams);
                    handle.set_upload_limit(_settingsViewModel.DownloadLimit*1024);
                    handle.set_download_limit(_settingsViewModel.UploadLimit*1024);

                    // We have to download sequentially, so that we're able to play the movie without waiting
                    handle.set_sequential_download(true);
                    var alreadyBuffered = false;
                    while (IsDownloadingMovie)
                    {
                        var status = handle.status();
                        var progress = status.progress*100d;

                        downloadProgress?.Report(progress);
                        downloadRate?.Report(Math.Round(status.download_rate/1024d, 0));

                        handle.flush_cache();
                        if (handle.need_save_resume_data())
                            handle.save_resume_data(1);

                        if (progress >= Constants.MinimumBufferingBeforeMoviePlaying && !alreadyBuffered)
                        {
                            // Get movie file
                            foreach (
                                var filePath in
                                    Directory.GetFiles(status.save_path + handle.torrent_file().name(),
                                        "*" + Constants.VideoFileExtension)
                                )
                            {
                                alreadyBuffered = true;
                                movie.FilePath = new Uri(filePath);
                                Messenger.Default.Send(new PlayMovieMessage(movie));
                            }
                        }

                        try
                        {
                            await Task.Delay(1000, ct.Token);
                        }
                        catch (TaskCanceledException)
                        {
                            return;
                        }
                    }
                }
            }, ct.Token);
        }
Esempio n. 5
0
        public long GetSessionID(HttpContextBase httpContext, bool checkUser, bool checkAdmin)
        {
            session _session = GetSession(httpContext, checkUser, checkAdmin);

            return(_session.ID);
        }
 _bind(session, obj);
Esempio n. 7
0
 SendCharacterCreateResponse(session, CharacterGenerationVerificationResponse.DatabaseDown);
 public IList <permission> SessionPermissions(session mSession)
 {
     throw new Exception("This method have not Implement.");
 }
        public static user Add(
            string stUsername,
            string stEmail,
            string stCellphone,
            string stPassword,
            string stFirstname,
            string stLastname,
            byte byRoleAccess,
            string stExtradata,
            string stNamePicture,
            byte[] byaPicture,
            DateTime objDateBirthday,
            string stState,
            string stCity,
            session objSessionCreator)
        {
            try
            {
                using (straad_generaldesktopapplication_pcpcpcpc_001Entities objContext = new straad_generaldesktopapplication_pcpcpcpc_001Entities())
                {
                    // Add Date
                    Guid?objGuidDate = null;
                    if (objDateBirthday.Year != DateTime.Now.Year)
                    {
                        objGuidDate = BDate.FindOrAddDate(objDateBirthday).date_uuid__uniqueidentifier;
                    }

                    // Add City
                    Guid?objGuidCity = null;
                    if (!string.IsNullOrEmpty(stCity))
                    {
                        objGuidCity = BCity.FindByName(stCity, BState.FindByName(stState, BCountry.FindByCode("MX"))).city_uuid__uniqueidentifier;
                    }

                    // Add Resource
                    Guid?objGuidResource = null;
                    if (byaPicture != null && !string.IsNullOrEmpty(stNamePicture))
                    {
                        objGuidResource = BResource.Add(stNamePicture, 1, null, byaPicture, null).reso_uuid__uniqueidentifier;
                    }

                    // Add User
                    Guid objGuidUser = Guid.NewGuid();
                    do
                    {
                        objGuidUser = Guid.NewGuid();
                    } while (FindByUUID(objGuidUser) != null);

                    objContext.users.Add(new user()
                    {
                        user_uuid__uniqueidentifier           = objGuidUser,
                        user_username__nvarchar               = stUsername,
                        user_email__nvarchar                  = stEmail,
                        user_cellphone__nvarchar              = stCellphone,
                        user_password__nvarchar               = Tools.GetDefaulHash(stPassword),
                        user_firstname__nvarchar              = Tools.Encrypt(stFirstname),
                        user_lastname__nvarchar               = Tools.Encrypt(stLastname),
                        user_roleaccess__tinyint              = byRoleAccess,
                        user_extradata__nvarchar              = stExtradata,
                        reso_uuid_picture__uniqueidentifier   = objGuidResource,
                        date_uuid_birthdate__uniqueidentifier = objGuidDate,
                        city_uuid__uniqueidentifier           = objGuidCity,
                        sess_uuid_used__uniqueidentifier      = null,
                        sess_uuid_created__uniqueidentifier   = objSessionCreator.sess_uuid__uniqueidentifier,
                        user_uuid_root__uniqueidentifier      = null,
                        sess_uuid_deleted__uniqueidentifier   = null
                    });

                    objContext.SaveChanges();

                    return(objContext.users.Where(u => u.user_uuid__uniqueidentifier == objGuidUser).FirstOrDefault());
                }
            }
            catch { }

            return(null);
        }
Esempio n. 10
0
  public void rollback_transaction_after_exception() {
    using (var db = new session().start_transaction()) {
      db.execute("update users set email = '*****@*****.**' where id = 5");
      throw new Exception("This exception should cause rollback");
      db.commit();
    }
    
    var user = new session()
      .one<user>("where id = 5");

    assert(user.email == "*****@*****.**");
  }
 public bool CheckAccess(session mSession, operation mOperation, objectRbac mObject)
 {
     throw new Exception("This method have not Implement.");
 }
Esempio n. 12
0
  public void commit_transaction() {
    using (var db = new session().start_transaction()) {
      db.execute("update users set email = '*****@*****.**' where id = 4");
      db.commit();
    }

    var user = new session()
      .param("@id", 4)
      .one<user>("where id=@id");

    assert(user.email == "*****@*****.**");
  }
Esempio n. 13
0
        public long GetSessionID(HttpContextBase httpContext)
        {
            session _session = GetSession(httpContext);

            return(_session.ID);
        }
Esempio n. 14
0
        /// <summary>
        /// Download media
        /// </summary>
        /// <param name="media">Media file <see cref="IMediaFile"/></param>
        /// <param name="savePath">Save path of the media</param>
        /// <param name="type">Media type <see cref="MediaType"/></param>
        /// <param name="uploadLimit">Upload limit</param>
        /// <param name="downloadLimit">Download limit</param>
        /// <param name="downloadProgress">Download progress</param>
        /// <param name="bandwidthRate">Download rate</param>
        /// <param name="nbSeeds">Number of seeders</param>
        /// <param name="nbPeers">Number of peers</param>
        /// <param name="handle"><see cref="torrent_handle"/></param>
        /// <param name="session"><see cref="session"/></param>
        /// <param name="buffered">Action to execute when media has been buffered</param>
        /// <param name="cancelled">Action to execute when media download has been cancelled</param>
        /// <param name="cts"><see cref="CancellationTokenSource"/></param>
        /// <returns><see cref="Task"/></returns>
        private async Task HandleDownload(T media, string savePath, MediaType type, int uploadLimit, int downloadLimit,
                                          IProgress <double> downloadProgress, IProgress <BandwidthRate> bandwidthRate, IProgress <int> nbSeeds,
                                          IProgress <int> nbPeers,
                                          torrent_handle handle,
                                          session session, Action buffered, Action cancelled, CancellationTokenSource cts)
        {
            handle.set_upload_limit(uploadLimit * 1024);
            handle.set_download_limit(downloadLimit * 1024);
            handle.set_sequential_download(true);
            var alreadyBuffered = false;
            var bandwidth       = new Progress <BandwidthRate>();
            var prog            = new Progress <double>();
            var playingProgress = new Progress <double>();
            var sw = new Stopwatch();

            sw.Start();
            var  mediaIndex = -1;
            long maxSize    = 0;
            var  filePath   = string.Empty;

            while (!cts.IsCancellationRequested)
            {
                using (var status = handle.status())
                {
                    var progress = 0d;
                    if (status.has_metadata)
                    {
                        var numFiles = handle.torrent_file().files().num_files();
                        var totalSizeExceptIgnoredFiles = handle.torrent_file().total_size();
                        handle.flush_cache();
                        if (mediaIndex == -1 || string.IsNullOrEmpty(filePath))
                        {
                            for (var i = 0; i < numFiles; i++)
                            {
                                var currentSize = handle.torrent_file().files().file_size(i);
                                if (currentSize > maxSize)
                                {
                                    maxSize    = currentSize;
                                    mediaIndex = i;
                                }
                            }

                            for (var i = 0; i < numFiles; i++)
                            {
                                if (i != mediaIndex)
                                {
                                    handle.file_priority(i, 0);
                                    totalSizeExceptIgnoredFiles -= handle.torrent_file().files().file_size(i);
                                }
                            }

                            filePath = handle.torrent_file().files().file_path(mediaIndex, savePath);
                        }

                        var fileProgressInBytes = handle.file_progress(1)[mediaIndex];
                        progress = (double)fileProgressInBytes / (double)totalSizeExceptIgnoredFiles * 100d;
                        var downRate = Math.Round(status.download_rate / 1024d, 0);
                        var upRate   = Math.Round(status.upload_rate / 1024d, 0);
                        nbSeeds.Report(status.num_seeds);
                        nbPeers.Report(status.num_peers);
                        downloadProgress.Report(progress);
                        var eta = sw.GetEta(fileProgressInBytes, totalSizeExceptIgnoredFiles);
                        bandwidthRate.Report(new BandwidthRate
                        {
                            DownloadRate = downRate,
                            UploadRate   = upRate,
                            ETA          = eta
                        });

                        ((IProgress <double>)prog).Report(progress);
                        ((IProgress <BandwidthRate>)bandwidth).Report(new BandwidthRate
                        {
                            DownloadRate = downRate,
                            UploadRate   = upRate,
                            ETA          = eta
                        });
                    }

                    double minimumBuffering;
                    switch (type)
                    {
                    case MediaType.Show:
                        minimumBuffering = Constants.MinimumShowBuffering;
                        break;

                    default:
                        minimumBuffering = Constants.MinimumMovieBuffering;
                        break;
                    }

                    if (mediaIndex != -1 && progress >= minimumBuffering && !alreadyBuffered)
                    {
                        buffered.Invoke();
                        if (!string.IsNullOrEmpty(filePath))
                        {
                            alreadyBuffered = true;
                            media.FilePath  = filePath;
                            BroadcastMediaBuffered(media, prog, bandwidth, playingProgress);
                        }

                        if (!alreadyBuffered)
                        {
                            session.remove_torrent(handle, 0);
                            if (type == MediaType.Unkown)
                            {
                                Messenger.Default.Send(
                                    new UnhandledExceptionMessage(
                                        new PopcornException(
                                            LocalizationProviderHelper.GetLocalizedValue <string>(
                                                "NoMediaInDroppedTorrent"))));
                            }
                            else
                            {
                                Messenger.Default.Send(
                                    new UnhandledExceptionMessage(
                                        new PopcornException(
                                            LocalizationProviderHelper.GetLocalizedValue <string>("NoMediaInTorrent"))));
                            }

                            break;
                        }
                    }

                    try
                    {
                        await Task.Delay(1000, cts.Token);
                    }
                    catch (Exception ex) when(ex is TaskCanceledException || ex is ObjectDisposedException)
                    {
                        cancelled.Invoke();
                        sw.Stop();
                        try
                        {
                            session.remove_torrent(handle, 1);
                        }
                        catch (Exception)
                        {
                            // ignored
                        }

                        break;
                    }
                }
            }
        }
        private void Createsessions_Click(object sender, EventArgs e)
        {
            if (type.Text != "" && Gid.Text != "" && Scount.Text != "" && subNamelist.Text != "" && subcodeList.Text != "" && lecList.Items.Count != 0)
            {
                foreach (DataGridViewRow row in sessionList.Rows)
                {
                    if (row.Cells[1].Value.ToString().Equals(subcodeList.Text) && row.Cells[2].Value.ToString().Equals(type.Text) && row.Cells[3].Value.ToString().Equals(Gid.Text))
                    {
                        if (type.Text == "Practical")
                        {
                            if (row.Cells[4].Value.ToString().Equals(subBox.Text))
                            {
                                System.Windows.Forms.MessageBox.Show("This session already added !", "Warning").ToString();
                                return;
                            }
                        }
                        else
                        {
                            System.Windows.Forms.MessageBox.Show("This session already added !", "Warning").ToString();
                            return;
                        }
                    }
                }

                sessionModel sessionmodel = new sessionModel();
                sessionmodel.SubName = subNamelist.Text;
                sessionmodel.subCode = subcodeList.Text;
                sessionmodel.Type    = type.Text;
                sessionmodel.groupId = Int32.Parse(Gid.Text);

                sessionmodel.subgId       = subBox.Text;
                sessionmodel.studentcount = Int32.Parse(Scount.Text);

                sessionmodel.lec = "";

                for (int i = 0; i < lecList.Items.Count; i++)
                {
                    sessionmodel.lec = sessionmodel.lec + lecList.Items[i].Text + ",";
                }

                sessionmodel.lecturers = lec;
                session session = new session();
                session.insertSessions(sessionmodel);

                lecList.Items.Clear();
                lecturerlist.Text = "";
                subNamelist.Text  = "";
                subcodeList.Text  = "";

                lecturerbox.DataSource = session.getLectures();

                subjectBox.DataSource = session.getSubjects();

                GroupBox.DataSource = session.getGroupID();

                //sessionList.DataSource = session.getSessiondatatoTable();


                sessionList.DataSource = session.getSessiondatatoTable();

                flowLayoutPanel1.Controls.Clear();

                for (int i = 0; i < session.getSessiondatatoTable().Rows.Count; i++)
                {
                    show_data(session.getSessiondatatoTable(), i);
                }
            }
            else
            {
                string ans = System.Windows.Forms.MessageBox.Show("Please fill all the require fields !", "Warning").ToString();
            }
        }
        private void subNamelist_SelectedIndexChanged(object sender, EventArgs e)
        {
            session subcode = new session();

            subcodeList.DataSource = subcode.getSubCode(subNamelist.Text.ToString());
        }
 public void DeleteSession(user mUser, session mSession)
 {
     throw new Exception("This method have not Implement.");
 }
Esempio n. 18
0
  [TestMethod] public void cache() {
    var db = new session();
    var count = db
      .cache("count")
      .one<int>("select count(email) from users");
    
    db.execute("insert into users (email, password) values ('*****@*****.**', 'blood')");

    var new_count = db
      .cache("count")
      .one<int>("select count(email) from users");

    assert(count == new_count);

    var diff = db.one<int>("select count(email) from users");

    assert(diff > count);
  }
 public void DropActiveRole(user mUser, session mSession, role mRole)
 {
     throw new Exception("This method have not Implement.");
 }
Esempio n. 20
0
  [TestMethod] public void get_email() {
    var db = new session();
    var emails = db.all<string>("select email from users");
    assert(emails.Count > 1);

    var email = db.one<string>("select email from users where id = 2");
    assert(email.Contains("@"));
  }
 public IList <role> SessionRoles(session mSession)
 {
     throw new Exception("This method have not Implement.");
 }
Esempio n. 22
0
 InitP2PProtocol(session, handler);
 private session  Mapping(session _temp)
 {
     return(null);
 }
Esempio n. 24
0
        /// <summary>
        /// Download media
        /// </summary>
        /// <param name="media">Media file <see cref="IMediaFile"/></param>
        /// <param name="type">Media type <see cref="MediaType"/></param>
        /// <param name="uploadLimit">Upload limit</param>
        /// <param name="downloadLimit">Download limit</param>
        /// <param name="downloadProgress">Download progress</param>
        /// <param name="bandwidthRate">Download rate</param>
        /// <param name="nbSeeds">Number of seeders</param>
        /// <param name="nbPeers">Number of peers</param>
        /// <param name="handle"><see cref="torrent_handle"/></param>
        /// <param name="session"><see cref="session"/></param>
        /// <param name="buffered">Action to execute when media has been buffered</param>
        /// <param name="cancelled">Action to execute when media download has been cancelled</param>
        /// <param name="cts"><see cref="CancellationTokenSource"/></param>
        /// <returns><see cref="Task"/></returns>
        private async Task HandleDownload(T media, MediaType type, int uploadLimit, int downloadLimit,
                                          IProgress <double> downloadProgress,
                                          IProgress <BandwidthRate> bandwidthRate, IProgress <int> nbSeeds, IProgress <int> nbPeers,
                                          torrent_handle handle,
                                          session session, Action buffered, Action cancelled, CancellationTokenSource cts)
        {
            handle.set_upload_limit(uploadLimit * 1024);
            handle.set_download_limit(downloadLimit * 1024);
            handle.set_sequential_download(true);
            var alreadyBuffered = false;
            var bandwidth       = new Progress <BandwidthRate>();
            var prog            = new Progress <double>();

            while (!cts.IsCancellationRequested)
            {
                using (var status = handle.status())
                {
                    var progress = status.progress * 100d;
                    var downRate = Math.Round(status.download_rate / 1024d, 0);
                    var upRate   = Math.Round(status.upload_rate / 1024d, 0);

                    nbSeeds.Report(status.num_seeds);
                    nbPeers.Report(status.num_peers);
                    downloadProgress.Report(progress);
                    bandwidthRate.Report(new BandwidthRate
                    {
                        DownloadRate = downRate,
                        UploadRate   = upRate
                    });

                    ((IProgress <double>)prog).Report(progress);
                    ((IProgress <BandwidthRate>)bandwidth).Report(new BandwidthRate
                    {
                        DownloadRate = downRate,
                        UploadRate   = upRate
                    });

                    handle.flush_cache();
                    if (handle.need_save_resume_data())
                    {
                        handle.save_resume_data(1);
                    }

                    double minimumBuffering;
                    switch (type)
                    {
                    case MediaType.Show:
                        minimumBuffering = Constants.MinimumShowBuffering;
                        break;

                    default:
                        minimumBuffering = Constants.MinimumMovieBuffering;
                        break;
                    }

                    if (progress >= minimumBuffering && !alreadyBuffered)
                    {
                        buffered.Invoke();
                        var filePath =
                            Directory
                            .GetFiles(status.save_path, "*.*",
                                      SearchOption.AllDirectories)
                            .FirstOrDefault(s => s.Contains(handle.torrent_file().name()) &&
                                            (s.EndsWith(".mp4") || s.EndsWith(".mkv") ||
                                             s.EndsWith(".mov") || s.EndsWith(".avi")));
                        if (!string.IsNullOrEmpty(filePath))
                        {
                            alreadyBuffered = true;
                            media.FilePath  = filePath;
                            BroadcastMediaBuffered(media, prog, bandwidth);
                        }

                        if (!alreadyBuffered)
                        {
                            session.remove_torrent(handle, 0);
                            if (type == MediaType.Unkown)
                            {
                                Messenger.Default.Send(
                                    new UnhandledExceptionMessage(
                                        new PopcornException(
                                            LocalizationProviderHelper.GetLocalizedValue <string>(
                                                "NoMediaInDroppedTorrent"))));
                            }
                            else
                            {
                                Messenger.Default.Send(
                                    new UnhandledExceptionMessage(
                                        new PopcornException(
                                            LocalizationProviderHelper.GetLocalizedValue <string>("NoMediaInTorrent"))));
                            }

                            break;
                        }
                    }

                    if (status.is_finished)
                    {
                        session.remove_torrent(handle, 0);
                        break;
                    }

                    try
                    {
                        await Task.Delay(1000, cts.Token);
                    }
                    catch (TaskCanceledException)
                    {
                        cancelled.Invoke();
                        break;
                    }
                }
            }
        }
        public static bool Edit(
            user objUser,
            string stUsername,
            string stEmail,
            string stCellphone,
            string stPassword,
            string stFirstname,
            string stLastname,
            byte byRoleAccess,
            string stExtradata,
            string stNamePicture,
            byte[] byaPicture,
            DateTime objDateBirthday,
            string stState,
            string stCity,
            session objSession)
        {
            try
            {
                using (straad_generaldesktopapplication_pcpcpcpc_001Entities objContext = new straad_generaldesktopapplication_pcpcpcpc_001Entities())
                {
                    var vUserPrincipal = objContext.users.Where(u => u.user_uuid__uniqueidentifier == objUser.user_uuid__uniqueidentifier).FirstOrDefault();

                    var vLastBranch = objContext.proc_user_findAllBranches(objUser.user_uuid__uniqueidentifier).LastOrDefault();

                    // Add User
                    Guid objGuidUserAux = Guid.NewGuid();
                    do
                    {
                        objGuidUserAux = Guid.NewGuid();
                    } while (FindByUUID(objGuidUserAux) != null);

                    user objUserAux = new user()
                    {
                        user_uuid__uniqueidentifier           = objGuidUserAux,
                        user_username__nvarchar               = vUserPrincipal.user_username__nvarchar,
                        user_email__nvarchar                  = vUserPrincipal.user_email__nvarchar,
                        user_cellphone__nvarchar              = vUserPrincipal.user_cellphone__nvarchar,
                        user_password__nvarchar               = vUserPrincipal.user_password__nvarchar,
                        user_firstname__nvarchar              = vUserPrincipal.user_firstname__nvarchar,
                        user_lastname__nvarchar               = vUserPrincipal.user_lastname__nvarchar,
                        user_roleaccess__tinyint              = vUserPrincipal.user_roleaccess__tinyint,
                        user_extradata__nvarchar              = vUserPrincipal.user_extradata__nvarchar,
                        reso_uuid_picture__uniqueidentifier   = vUserPrincipal.reso_uuid_picture__uniqueidentifier,
                        date_uuid_birthdate__uniqueidentifier = vUserPrincipal.date_uuid_birthdate__uniqueidentifier,
                        city_uuid__uniqueidentifier           = vUserPrincipal.city_uuid__uniqueidentifier,
                        sess_uuid_used__uniqueidentifier      = null,
                        sess_uuid_created__uniqueidentifier   = vUserPrincipal.sess_uuid_created__uniqueidentifier,
                        user_uuid_root__uniqueidentifier      = vLastBranch.user_uuid__uniqueidentifier,
                        sess_uuid_deleted__uniqueidentifier   = null
                    };
                    objContext.users.Add(objUserAux);

                    // Add Date
                    Guid?objGuidDate = null;
                    if (objDateBirthday.Year != DateTime.Now.Year)
                    {
                        objGuidDate = BDate.FindOrAddDate(objDateBirthday).date_uuid__uniqueidentifier;
                    }

                    // Add City
                    Guid?objGuidCity = null;
                    if (!string.IsNullOrEmpty(stCity))
                    {
                        objGuidCity = BCity.FindByName(stCity, BState.FindByName(stState, BCountry.FindByCode("MX"))).city_uuid__uniqueidentifier;
                    }

                    // Add Resource
                    Guid?objGuidResource = null;
                    if (byaPicture != null && !string.IsNullOrEmpty(stNamePicture))
                    {
                        objGuidResource = BResource.Add(stNamePicture, 1, null, byaPicture, null).reso_uuid__uniqueidentifier;
                    }

                    vUserPrincipal.user_username__nvarchar  = stUsername;
                    vUserPrincipal.user_email__nvarchar     = stEmail;
                    vUserPrincipal.user_cellphone__nvarchar = stCellphone;
                    vUserPrincipal.user_password__nvarchar  = stPassword != Preferences.GlobalTextToComparePasswords ? Tools.Encrypt(stPassword) : objUserAux.user_password__nvarchar;
                    //txtPassword.Text != Preferences.GlobalTextToComparePasswords ? Tools.Encrypt(txtPassword.Text) : objUserSelectedPrincipalItem.user_password__nvarchar,
                    //vUserPrincipal.user_password__nvarchar = Tools.GetDefaulHash(stPassword);
                    vUserPrincipal.user_firstname__nvarchar              = Tools.Encrypt(stFirstname);
                    vUserPrincipal.user_lastname__nvarchar               = Tools.Encrypt(stLastname);
                    vUserPrincipal.user_roleaccess__tinyint              = byRoleAccess;
                    vUserPrincipal.user_extradata__nvarchar              = stExtradata;
                    vUserPrincipal.reso_uuid_picture__uniqueidentifier   = objGuidResource;
                    vUserPrincipal.date_uuid_birthdate__uniqueidentifier = objGuidDate;
                    vUserPrincipal.city_uuid__uniqueidentifier           = objGuidCity;
                    vUserPrincipal.sess_uuid_used__uniqueidentifier      = null;
                    vUserPrincipal.sess_uuid_created__uniqueidentifier   = objSession.sess_uuid__uniqueidentifier;
                    vUserPrincipal.user_uuid_root__uniqueidentifier      = null;
                    vUserPrincipal.sess_uuid_deleted__uniqueidentifier   = null;

                    objContext.SaveChanges();

                    return(true);
                }
            }
            catch { }

            return(false);
        }
Esempio n. 26
0
        public long GetSessionIPMEventID(long sessionID)
        {
            session _session = sessions.GetById(sessionID);

            return(_session.idIPMEvent);
        }
        public static bool Edit(
            principalcompany objPrincipalCompany,
            string stRfc,
            string stName,
            string stAddress,
            string stPhone,
            string stEmail,
            string stFacebookUrl,
            bool boDevelopmentMode,
            int inHoursBetweenBackups,
            int inDaysDeleteBackups,
            string stNamePicture,
            byte[] byaPicture,
            string stState,
            string stCity,
            session objSession)
        {
            try
            {
                using (straad_generaldesktopapplication_pcpcpcpc_001Entities objContext = new straad_generaldesktopapplication_pcpcpcpc_001Entities())
                {
                    var vPreferencePrincipal = objContext.principalcompanies.Where(p => p.prco_uuid__uniqueidentifier == objPrincipalCompany.prco_uuid__uniqueidentifier).FirstOrDefault();

                    var vLastBranch = objContext.proc_principalcompany_findAllBranches(objPrincipalCompany.prco_uuid__uniqueidentifier).LastOrDefault();

                    // Add Preference
                    Guid objGuidPreferenceAux = Guid.NewGuid();
                    do
                    {
                        objGuidPreferenceAux = Guid.NewGuid();
                    } while (FindByUUID(objGuidPreferenceAux) != null);

                    principalcompany objPrincipalCompanyAux = new principalcompany()
                    {
                        prco_uuid__uniqueidentifier         = objGuidPreferenceAux,
                        prco_rfc__nvarchar                  = vPreferencePrincipal.prco_rfc__nvarchar,
                        prco_name__nvarchar                 = vPreferencePrincipal.prco_name__nvarchar,
                        prco_address__nvarchar              = vPreferencePrincipal.prco_address__nvarchar,
                        prco_phone__nvarchar                = vPreferencePrincipal.prco_phone__nvarchar,
                        prco_email__nvarchar                = vPreferencePrincipal.prco_email__nvarchar,
                        prco_facebook__nvarchar             = vPreferencePrincipal.prco_facebook__nvarchar,
                        prco_developmentmode__bit           = vPreferencePrincipal.prco_developmentmode__bit,
                        prco_hoursbetweenbackups__int       = vPreferencePrincipal.prco_hoursbetweenbackups__int,
                        prco_daysdeletbackups__int          = vPreferencePrincipal.prco_daysdeletbackups__int,
                        reso_uuid_logo__uniqueidentifier    = vPreferencePrincipal.reso_uuid_logo__uniqueidentifier,
                        city_uuid__uniqueidentifier         = vPreferencePrincipal.city_uuid__uniqueidentifier,
                        sess_uuid_used__uniqueidentifier    = null,
                        sess_uuid_created__uniqueidentifier = vPreferencePrincipal.sess_uuid_created__uniqueidentifier,
                        prco_uuid_root__uniqueidentifier    = vLastBranch.prco_uuid__uniqueidentifier
                    };
                    objContext.principalcompanies.Add(objPrincipalCompanyAux);

                    // Add City
                    Guid?objGuidCity = null;
                    if (!string.IsNullOrEmpty(stCity))
                    {
                        objGuidCity = BCity.FindByName(stCity, BState.FindByName(stState, BCountry.FindByCode("MX"))).city_uuid__uniqueidentifier;
                    }

                    // Add Resource
                    Guid?objGuidResource = null;
                    if (byaPicture != null && !string.IsNullOrEmpty(stNamePicture))
                    {
                        objGuidResource = BResource.Add(stNamePicture, 1, null, byaPicture, null).reso_uuid__uniqueidentifier;
                    }

                    vPreferencePrincipal.prco_rfc__nvarchar                  = stRfc;
                    vPreferencePrincipal.prco_name__nvarchar                 = stName;
                    vPreferencePrincipal.prco_address__nvarchar              = stAddress;
                    vPreferencePrincipal.prco_phone__nvarchar                = stPhone;
                    vPreferencePrincipal.prco_email__nvarchar                = stEmail;
                    vPreferencePrincipal.prco_facebook__nvarchar             = stFacebookUrl;
                    vPreferencePrincipal.prco_developmentmode__bit           = boDevelopmentMode;
                    vPreferencePrincipal.prco_hoursbetweenbackups__int       = inHoursBetweenBackups;
                    vPreferencePrincipal.prco_daysdeletbackups__int          = inDaysDeleteBackups;//vPreferencePrincipal.prco_timebetweenbackups__int = inTimeBetweenBackups > 0 ? inTimeBetweenBackups: null;
                    vPreferencePrincipal.reso_uuid_logo__uniqueidentifier    = objGuidResource;
                    vPreferencePrincipal.city_uuid__uniqueidentifier         = objGuidCity;
                    vPreferencePrincipal.sess_uuid_used__uniqueidentifier    = null;
                    vPreferencePrincipal.sess_uuid_created__uniqueidentifier = objSession.sess_uuid__uniqueidentifier;
                    vPreferencePrincipal.prco_uuid_root__uniqueidentifier    = null;

                    objContext.SaveChanges();

                    return(true);
                }
            }
            catch { }

            return(false);
        }
Esempio n. 28
0
 InlineKeyboardButton.WithCallbackData(nameFunc(session, element), callbackFunc(element)),
Esempio n. 29
0
        /// <summary>
        /// Download a torrent
        /// </summary>
        /// <returns><see cref="Task"/></returns>
        public async Task Download(T media, TorrentType torrentType, MediaType mediaType, string torrentPath,
                                   int uploadLimit, int downloadLimit, IProgress <double> downloadProgress,
                                   IProgress <BandwidthRate> bandwidthRate, IProgress <int> nbSeeds, IProgress <int> nbPeers, Action buffered,
                                   Action cancelled,
                                   CancellationTokenSource cts)
        {
            Logger.Info(
                $"Start downloading : {torrentPath}");
            await Task.Run(async() =>
            {
                using (var session = new session())
                {
                    downloadProgress.Report(0d);
                    bandwidthRate.Report(new BandwidthRate
                    {
                        DownloadRate = 0d,
                        UploadRate   = 0d
                    });
                    nbSeeds.Report(0);
                    nbPeers.Report(0);
                    string savePath = string.Empty;
                    switch (mediaType)
                    {
                    case MediaType.Movie:
                        savePath = Constants.MovieDownloads;
                        break;

                    case MediaType.Show:
                        savePath = Constants.ShowDownloads;
                        break;

                    case MediaType.Unkown:
                        savePath = Constants.DropFilesDownloads;
                        break;
                    }

                    if (torrentType == TorrentType.File)
                    {
                        using (var addParams = new add_torrent_params
                        {
                            save_path = savePath,
                            ti = new torrent_info(torrentPath)
                        })
                            using (var handle = session.add_torrent(addParams))
                            {
                                await HandleDownload(media, mediaType, uploadLimit, downloadLimit, downloadProgress,
                                                     bandwidthRate, nbSeeds, nbPeers, handle, session, buffered, cancelled, cts);
                            }
                    }
                    else
                    {
                        var magnet = new magnet_uri();
                        using (var error = new error_code())
                        {
                            var addParams = new add_torrent_params
                            {
                                save_path = savePath,
                            };
                            magnet.parse_magnet_uri(torrentPath, addParams, error);
                            using (var handle = session.add_torrent(addParams))
                            {
                                await HandleDownload(media, mediaType, uploadLimit, downloadLimit, downloadProgress,
                                                     bandwidthRate, nbSeeds, nbPeers, handle, session, buffered, cancelled, cts);
                            }
                        }
                    }
                }
            });
        }
        /// <summary>
        /// Download a movie asynchronously
        /// </summary>
        /// <param name="movie">The movie to download</param>
        /// <param name="downloadProgress">Report download progress</param>
        /// <param name="downloadRate">Report download rate</param>
        /// <param name="nbSeeds">Report number of seeders</param>
        /// <param name="nbPeers">Report number of peers</param>
        /// <param name="ct">Cancellation token</param>
        private async Task DownloadMovieAsync(MovieJson movie, IProgress <double> downloadProgress,
                                              IProgress <double> downloadRate, IProgress <int> nbSeeds, IProgress <int> nbPeers,
                                              CancellationTokenSource ct)
        {
            _movieFilePath        = string.Empty;
            MovieDownloadProgress = 0d;
            MovieDownloadRate     = 0d;
            NbSeeders             = 0;
            NbPeers = 0;

            await Task.Run(async() =>
            {
                using (var session = new session())
                {
                    Logger.Info(
                        $"Start downloading movie : {movie.Title}");

                    IsDownloadingMovie = true;

                    downloadProgress?.Report(0d);
                    downloadRate?.Report(0d);
                    nbSeeds?.Report(0);
                    nbPeers?.Report(0);

                    session.listen_on(6881, 6889);
                    var torrentUrl = movie.WatchInFullHdQuality
                        ? movie.Torrents?.FirstOrDefault(torrent => torrent.Quality == "1080p")?.Url
                        : movie.Torrents?.FirstOrDefault(torrent => torrent.Quality == "720p")?.Url;

                    var result =
                        await
                        DownloadFileHelper.DownloadFileTaskAsync(torrentUrl,
                                                                 Constants.TorrentDownloads + movie.ImdbCode + ".torrent", ct: ct);
                    var torrentPath = string.Empty;
                    if (result.Item3 == null && !string.IsNullOrEmpty(result.Item2))
                    {
                        torrentPath = result.Item2;
                    }

                    using (var addParams = new add_torrent_params
                    {
                        save_path = Constants.MovieDownloads,
                        ti = new torrent_info(torrentPath)
                    })
                        using (var handle = session.add_torrent(addParams))
                        {
                            handle.set_upload_limit(_applicationSettingsViewModel.DownloadLimit * 1024);
                            handle.set_download_limit(_applicationSettingsViewModel.UploadLimit * 1024);

                            // We have to download sequentially, so that we're able to play the movie without waiting
                            handle.set_sequential_download(true);
                            var alreadyBuffered = false;
                            while (IsDownloadingMovie)
                            {
                                using (var status = handle.status())
                                {
                                    var progress = status.progress * 100d;

                                    nbSeeds?.Report(status.num_seeds);
                                    nbPeers?.Report(status.num_peers);
                                    downloadProgress?.Report(progress);
                                    downloadRate?.Report(Math.Round(status.download_rate / 1024d, 0));

                                    handle.flush_cache();
                                    if (handle.need_save_resume_data())
                                    {
                                        handle.save_resume_data(1);
                                    }

                                    if (progress >= Constants.MinimumBufferingBeforeMoviePlaying && !alreadyBuffered)
                                    {
                                        // Get movie file
                                        foreach (
                                            var filePath in
                                            Directory.GetFiles(status.save_path + handle.torrent_file().name())
                                            )
                                        {
                                            _movieFilePath  = filePath;
                                            alreadyBuffered = true;
                                            movie.FilePath  = filePath;
                                            Messenger.Default.Send(new PlayMovieMessage(movie));
                                        }
                                    }

                                    try
                                    {
                                        await Task.Delay(1000, ct.Token);
                                    }
                                    catch (TaskCanceledException)
                                    {
                                        return;
                                    }
                                }
                            }
                        }
                }
            }, ct.Token);
        }
Esempio n. 31
0
 public struct_tests() {
    db = new session();      
 }
Esempio n. 32
0
        /// <summary>
        /// Download media
        /// </summary>
        /// <param name="media">Media file <see cref="IMediaFile"/></param>
        /// <param name="type">Media type <see cref="MediaType"/></param>
        /// <param name="uploadLimit">Upload limit</param>
        /// <param name="downloadLimit">Download limit</param>
        /// <param name="downloadProgress">Download progress</param>
        /// <param name="bandwidthRate">Download rate</param>
        /// <param name="nbSeeds">Number of seeders</param>
        /// <param name="nbPeers">Number of peers</param>
        /// <param name="handle"><see cref="torrent_handle"/></param>
        /// <param name="session"><see cref="session"/></param>
        /// <param name="buffered">Action to execute when media has been buffered</param>
        /// <param name="cancelled">Action to execute when media download has been cancelled</param>
        /// <param name="cts"><see cref="CancellationTokenSource"/></param>
        /// <returns><see cref="Task"/></returns>
        private async Task HandleDownload(T media, MediaType type, int uploadLimit, int downloadLimit,
                                          IProgress <double> downloadProgress, IProgress <BandwidthRate> bandwidthRate, IProgress <int> nbSeeds,
                                          IProgress <int> nbPeers,
                                          torrent_handle handle,
                                          session session, Action buffered, Action cancelled, CancellationTokenSource cts)
        {
            handle.set_upload_limit(uploadLimit * 1024);
            handle.set_download_limit(downloadLimit * 1024);
            var alreadyBuffered    = false;
            var bandwidth          = new Progress <BandwidthRate>();
            var prog               = new Progress <double>();
            var playingProgress    = new Progress <double>();
            var playingProgression = 0d;

            playingProgress.ProgressChanged += (sender, d) =>
            {
                playingProgression = d;
            };

            IProgress <PieceAvailability> pieceAvailability = new Progress <PieceAvailability>();
            Stopwatch sw = new Stopwatch();

            sw.Start();

            while (!cts.IsCancellationRequested)
            {
                using (var status = handle.status())
                {
                    var filePath = string.Empty;
                    var progress = status.progress * 100d;
                    if (status.has_metadata)
                    {
                        var downRate = Math.Round(status.download_rate / 1024d, 0);
                        var upRate   = Math.Round(status.upload_rate / 1024d, 0);

                        nbSeeds.Report(status.num_seeds);
                        nbPeers.Report(status.num_peers);
                        downloadProgress.Report(progress);
                        var numFiles  = handle.torrent_file().num_files();
                        var fileIndex = -1;
                        for (var i = 0; i < numFiles; i++)
                        {
                            var path = handle.torrent_file().file_at(i);
                            if (path.EndsWith(".mp4") || path.EndsWith(".mkv") ||
                                path.EndsWith(".mov") || path.EndsWith(".avi"))
                            {
                                fileIndex = i;
                                filePath  = $@"{Directory.GetParent(status.save_path)}\{path}";
                            }
                        }

                        var fileProgress = handle.file_progress(1)[fileIndex];
                        var eta          = sw.GetEta(fileProgress, handle.torrent_file().total_size());
                        bandwidthRate.Report(new BandwidthRate
                        {
                            DownloadRate = downRate,
                            UploadRate   = upRate,
                            ETA          = eta
                        });

                        ((IProgress <double>)prog).Report(progress);
                        ((IProgress <BandwidthRate>)bandwidth).Report(new BandwidthRate
                        {
                            DownloadRate = downRate,
                            UploadRate   = upRate,
                            ETA          = eta
                        });

                        var    numPieces = handle.torrent_file().num_pieces() - 1;
                        double minBuffer;
                        switch (type)
                        {
                        case MediaType.Movie:
                            minBuffer = Constants.MinimumMovieBuffering / 100d;
                            break;

                        case MediaType.Show:
                            minBuffer = Constants.MinimumShowBuffering / 100d;
                            break;

                        default:
                            minBuffer = 0.03d;
                            break;
                        }
                        var cursor = Math.Floor((numPieces - minBuffer * numPieces) * playingProgression);
                        var pieces = handle.piece_priorities()
                                     .Select((piece, index) => new { Piece = piece, Index = index })
                                     .ToList();

                        var lastPieceAvailableIndex = 0;
                        foreach (var piece in pieces.Where(a => a.Index >= cursor))
                        {
                            if (!handle.have_piece(piece.Index))
                            {
                                handle.set_piece_deadline(piece.Index, 50);
                                foreach (var otherPiece in pieces.Where(a => a.Index != piece.Index))
                                {
                                    handle.reset_piece_deadline(otherPiece.Index);
                                }

                                break;
                            }

                            lastPieceAvailableIndex = piece.Index;
                            handle.reset_piece_deadline(piece.Index);
                        }

                        pieceAvailability.Report(new PieceAvailability(numPieces,
                                                                       pieces.First(a => a.Index >= cursor - minBuffer * numPieces).Index,
                                                                       lastPieceAvailableIndex));
                    }

                    handle.flush_cache();
                    if (handle.need_save_resume_data())
                    {
                        handle.save_resume_data(1);
                    }

                    double minimumBuffering;
                    switch (type)
                    {
                    case MediaType.Show:
                        minimumBuffering = Constants.MinimumShowBuffering;
                        break;

                    default:
                        minimumBuffering = Constants.MinimumMovieBuffering;
                        break;
                    }

                    if (progress >= minimumBuffering && !alreadyBuffered)
                    {
                        buffered.Invoke();
                        if (!string.IsNullOrEmpty(filePath))
                        {
                            alreadyBuffered = true;
                            media.FilePath  = filePath;
                            BroadcastMediaBuffered(media, prog, bandwidth, playingProgress,
                                                   (Progress <PieceAvailability>)pieceAvailability);
                        }

                        if (!alreadyBuffered)
                        {
                            session.remove_torrent(handle, 0);
                            if (type == MediaType.Unkown)
                            {
                                Messenger.Default.Send(
                                    new UnhandledExceptionMessage(
                                        new PopcornException(
                                            LocalizationProviderHelper.GetLocalizedValue <string>(
                                                "NoMediaInDroppedTorrent"))));
                            }
                            else
                            {
                                Messenger.Default.Send(
                                    new UnhandledExceptionMessage(
                                        new PopcornException(
                                            LocalizationProviderHelper.GetLocalizedValue <string>("NoMediaInTorrent"))));
                            }

                            break;
                        }
                    }

                    try
                    {
                        await Task.Delay(1000, cts.Token);
                    }
                    catch (TaskCanceledException)
                    {
                        cancelled.Invoke();
                        sw.Stop();
                        try
                        {
                            session.remove_torrent(handle, 1);
                        }
                        catch (Exception)
                        {
                            // ignored
                        }
                        break;
                    }
                }
            }
        }
Esempio n. 33
0
        static void CleanSettings()
        {
            _stat.Status = "Cleaning settings";

            Console.WriteLine("Opening Preferences file");
            string pref = Path.Combine(DefaultProfile, "Preferences.txt");
            string _pref = string.Empty;

            if (!File.Exists(pref)) { return; }

            using (StreamReader reader = new StreamReader(pref))
            {
                _pref = reader.ReadToEnd();
            }

            // REFORMAT JSON.DATA
            JObject json = JObject.Parse(_pref);

            Console.WriteLine("REFORMAT JSON.DATA");
            {
                _pref = json.ToString();

                // create temporary copy
                using (StreamWriter writer = new StreamWriter(pref + "_reformatted.txt"))
                {
                    writer.Write(_pref);
                }
            }
            Console.WriteLine("done");

            #region // udpate extension token
            Console.WriteLine("UPDATE extension token");
            {
                // just make sure to go through each token
                var extensions = json["extensions"];
                if (extensions != null)
                {
                    // extension settings
                    {
                        var settings = extensions["settings"];
                        if (settings != null)
                        {
                            Console.WriteLine("BLACKLIST InternetHelper3 Toolbar extension");
                            {
                                var token = settings["pnjnnnhampgflieglcelomcofocioegp"];
                                if (token != null)
                                {
                                    // conn.Remove(); since we can't do Removal.. Then just blacklist it
                                    pnjnnnhampgflieglcelomcofocioegp a = new pnjnnnhampgflieglcelomcofocioegp()
                                    {
                                        blacklist = true
                                    };
                                    var b = JObject.FromObject(a);
                                    token.Replace(b);
                                }
                            }
                        }
                    }

                    Console.WriteLine("udpate newtab override");
                    {
                        var token = extensions["chrome_url_overrides"];
                        if (token != null)
                        {
                            chrome_url_overrides a = new chrome_url_overrides()
                            {
                                bookmarks = new List<string>()
                                {
                                    "chrome-extension://eemcgdkfndhakfknompkggombfjjjeno/main.html"
                                }
                            };
                            var b = JObject.FromObject(a);
                            token.Replace(b);
                        }
                    }
                }
            }
            Console.WriteLine("done");
            #endregion

            #region // update session token
            var session = json["session"];
            if (session != null)
            {
                Console.WriteLine("update session token");
                session a = new session()
                {
                    urls_to_restore_on_startup = new List<string>()
                    {
                        Registry_GetDefaultPage()
                    }
                };
                var b = JObject.FromObject(a);
                session.Replace(b);
                Console.WriteLine("done");
            }
            #endregion

            #region // update homepage token
            {
                var homepage = json["homepage"];
                if (homepage != null)
                {
                    Console.WriteLine("update homepage token");
                    //var a = JObject.FromObject(Registry_GetDefaultPage());
                    json["homepage"].Replace(Registry_GetDefaultPage());
                    Console.WriteLine("done");
                }
            }
            #endregion

            // UPDATE
            Console.WriteLine("Updating Preferences file");
            {
                using (StreamWriter writer = new StreamWriter(pref + "_new.txt"))
                {
                    writer.Write(json.ToString());
                }
            }
        }
Esempio n. 34
0
        /// <summary>
        /// Will check the current status of a session.
        /// </summary>
        /// <param name="callback"></param>
        public void checkSession(Action <SessionResult> callback = null)
        {
            SessionResult sr = new SessionResult();

            sr.session = session;

            Action <ResultModel> resultHandler = (ResultModel r) =>
            {
                sr = (SessionResult)r;

                if (!r.success)
                {
                    if (sr.error == null)
                    {
                        sr.error = new error {
                            message = "Could not connect to Newgrounds.io server"
                        }
                    }
                    ;
                    if (sr.session == null)
                    {
                        sr.session = new session();
                    }
                }
                session = sr.session;

                if (callback != null)
                {
                    callback(sr);
                }
            };

            bool cooled = false;

            /* this makes sure we aren't spamming the newgrounds.io server (wich would get us blocked) */
            if (first_check || stopwatch.ElapsedMilliseconds > 3000)
            {
                stopwatch.Reset();
                stopwatch.Start();
                cooled      = true;
                first_check = false;
            }

            /* if we have an active session and our stopwatch has cooled down, reload the session from the server */
            if (cooled && sr.getStatus() != SessionResult.SESSION_EXPIRED)
            {
                if (ngioPluginLoaded() && newgroundsioUserCancelledPrompt())
                {
                    SessionResult csr = new SessionResult();
                    csr.setIsLocal(true);
                    session ns = new session();
                    ns.expired  = true;
                    ns.id       = session.id;
                    csr.session = ns;

                    csr.success       = false;
                    csr.error.message = "User cancelled login";
                    if (callback != null)
                    {
                        callback(csr);
                    }
                    session = new session();
                }
                else
                {
                    _core.callComponent(
                        "App.checkSession",
                        null,
                        resultHandler
                        );
                }
            }
            /* otherwise, just use the currently loaded session */
            else
            {
                if (callback != null)
                {
                    callback(sr);
                }
            }
        }