StoryCode

VisualStudioCode에서 개발을 위한 설정

C#
반응형

1. VSC Extension 설치

2. dot net sdk 설치

https://dotnet.microsoft.com/download#windowscmd

 

3. 프로젝트용 폴더를 만들어서 들어간다음, 아래 명령 실행

dotnet new console 

 

4. 프로젝트 폴더에서 

cmd > code .

 

반응형

'C#' 카테고리의 다른 글

Install 을 위한 셋업파일 만들기  (0) 2019.07.30
SQLite 설치  (0) 2017.12.26
실행시 관리자 권한창 띄우기  (0) 2017.07.26

환경 설정 및 매뉴얼

C#/Capturing Web, Selenium
반응형

1.1) Nuget 에서 Selenium.WebDriver 설치

1.2) Nuget 에서 Selenium.Chrome 설치

 

1.3) Nuget 에서 Selenium.WebDriver.ChromeDriver 설치

 

1.4) DotNetSeleniumExtras.WaitHelpers 설치

 

4.1) 초기화

// NuGet: Selenium.WebDriver.ChromeDriver
using OpenQA.Selenium.Chrome;
IWebDriver driver = new ChromeDriver();
// NuGet: Selenium.Mozilla.Firefox.Webdriver
using OpenQA.Selenium.Firefox;
IWebDriver driver = new FirefoxDriver();
// NuGet: Selenium.WebDriver.PhantomJS
using OpenQA.Selenium.PhantomJS;
IWebDriver driver = new PhantomJSDriver();
// NuGet: Selenium.WebDriver.IEDriver
using OpenQA.Selenium.IE;
IWebDriver driver = new InternetExplorerDriver();
// NuGet: Selenium.WebDriver.EdgeDriver
using OpenQA.Selenium.Edge;
IWebDriver driver = new EdgeDriver();

4.2) Locators

this.driver.FindElement(By.ClassName("className"));
this.driver.FindElement(By.CssSelector("css"));
this.driver.FindElement(By.Id("id"));
this.driver.FindElement(By.LinkText("text"));
this.driver.FindElement(By.Name("name"));
this.driver.FindElement(By.PartialLinkText("pText"));
this.driver.FindElement(By.TagName("input"));
this.driver.FindElement(By.XPath("//*[@id='editor']"));
// Find multiple elements
IReadOnlyCollection<IWebElement> anchors = this.driver.FindElements(By.TagName("a"));
// Search for an element inside another
var div = this.driver.FindElement(By.TagName("div")).FindElement(By.TagName("a"));

4.3) 기본 객체 처리

IWebElement element = driver.FindElement(By.Id("id"));
element.Click();
element.SendKeys("someText");
element.Clear();
element.Submit();
string innerText = element.Text;
bool isEnabled = element.Enabled;
bool isDisplayed = element.Displayed;
bool isSelected = element.Selected;
IWebElement element = driver.FindElement(By.Id("id"));
SelectElement select = new SelectElement(element);
select.SelectByIndex(1);
select.SelectByText("Ford");
select.SelectByValue("ford");           
select.DeselectAll();
select.DeselectByIndex(1);
select.DeselectByText("Ford");
select.DeselectByValue("ford");
IWebElement selectedOption = select.SelectedOption;
IList<IWebElement> allSelected = select.AllSelectedOptions;
bool isMultipleSelect = select.IsMultiple;

4.4) 고급 객체 처리

// Drag and Drop
IWebElement element = 
driver.FindElement(By.XPath("//*[@id='project']/p[1]/div/div[2]"));
Actions move = new Actions(driver);
move.DragAndDropToOffset(element, 30, 0).Perform();
// How to check if an element is visible
Assert.IsTrue(driver.FindElement(By.XPath("//*[@id='tve_editor']/div")).Displayed);
// Upload a file
IWebElement element = driver.FindElement(By.Id("RadUpload1file0"));
String filePath = @"D:WebDriver.Series.TestsWebDriver.xml";
element.SendKeys(filePath);
// Scroll focus to control
IWebElement link = driver.FindElement(By.PartialLinkText("Previous post"));
string js = string.Format("window.scroll(0, {0});", link.Location.Y);
((IJavaScriptExecutor)driver).ExecuteScript(js);
link.Click();
// Taking an element screenshot
IWebElement element = driver.FindElement(By.XPath("//*[@id='tve_editor']/div"));
var cropArea = new Rectangle(element.Location, element.Size);
var bitmap = bmpScreen.Clone(cropArea, bmpScreen.PixelFormat);
bitmap.Save(fileName);
// Focus on a control
IWebElement link = driver.FindElement(By.PartialLinkText("Previous post"));
// Wait for visibility of an element
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
wait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(
By.XPath("//*[@id='tve_editor']/div[2]/div[2]/div/div")));

4.5) 기본 크롬 브라우저 처리

// Navigate to a page      
this.driver.Navigate().GoToUrl(@"http://google.com");
// Get the title of the page
string title = this.driver.Title;
// Get the current URL
string url = this.driver.Url;
// Get the current page HTML source
string html = this.driver.PageSource;

4.6) 고급 크롬 브라우저 처리

// Handle JavaScript pop-ups
IAlert a = driver.SwitchTo().Alert();
a.Accept();
a.Dismiss();
// Switch between browser windows or tabs
ReadOnlyCollection<string> windowHandles = driver.WindowHandles;
string firstTab = windowHandles.First();
string lastTab = windowHandles.Last();
driver.SwitchTo().Window(lastTab);
// Navigation history
this.driver.Navigate().Back();
this.driver.Navigate().Refresh();
this.driver.Navigate().Forward();
// Option 1.
link.SendKeys(string.Empty);
// Option 2.
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].focus();", link);
// Maximize window
this.driver.Manage().Window.Maximize();
// Add a new cookie
Cookie cookie = new OpenQA.Selenium.Cookie("key", "value");
this.driver.Manage().Cookies.AddCookie(cookie);
// Get all cookies
var cookies = this.driver.Manage().Cookies.AllCookies;
// Delete a cookie by name
this.driver.Manage().Cookies.DeleteCookieNamed("CookieName");
// Delete all cookies
this.driver.Manage().Cookies.DeleteAllCookies();
//Taking a full-screen screenshot
Screenshot screenshot = ((ITakesScreenshot)driver).GetScreenshot();
screenshot.SaveAsFile(@"pathToImage", ImageFormat.Png);
// Wait until a page is fully loaded via JavaScript
WebDriverWait wait = new WebDriverWait(this.driver, TimeSpan.FromSeconds(30));
wait.Until((x) =>
{
    return ((IJavaScriptExecutor)this.driver).ExecuteScript("return document.readyState").Equals("complete");
});
// Switch to frames
this.driver.SwitchTo().Frame(1);
this.driver.SwitchTo().Frame("frameName");
IWebElement element = this.driver.FindElement(By.Id("id"));
this.driver.SwitchTo().Frame(element);
// Switch to the default document
this.driver.SwitchTo().DefaultContent();

 

참조 : https://www.automatetheplanet.com/selenium-webdriver-csharp-cheat-sheet/

4.7) 브라우저 고급 처리

// Use a specific Firefox profile
FirefoxProfileManager profileManager = new FirefoxProfileManager();
FirefoxProfile profile = profileManager.GetProfile("HARDDISKUSER");
IWebDriver driver = new FirefoxDriver(profile);
// Set a HTTP proxy Firefox
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.SetPreference("network.proxy.type", 1);
firefoxProfile.SetPreference("network.proxy.http", "myproxy.com");
firefoxProfile.SetPreference("network.proxy.http_port", 3239);
IWebDriver driver = new FirefoxDriver(firefoxProfile);
// Set a HTTP proxy Chrome
ChromeOptions options = new ChromeOptions();
var proxy = new Proxy();
proxy.Kind = ProxyKind.Manual;
proxy.IsAutoDetect = false;
proxy.HttpProxy =
proxy.SslProxy = "127.0.0.1:3239";
options.Proxy = proxy;
options.AddArgument("ignore-certificate-errors");
IWebDriver driver = new ChromeDriver(options);
// Accept all certificates Firefox 
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.AcceptUntrustedCertificates = true;
firefoxProfile.AssumeUntrustedCertificateIssuer = false;
IWebDriver driver = new FirefoxDriver(firefoxProfile);
// Accept all certificates Chrome 
DesiredCapabilities capability = DesiredCapabilities.Chrome();
Environment.SetEnvironmentVariable("webdriver.chrome.driver", "C:PathToChromeDriver.exe");
capability.SetCapability(CapabilityType.AcceptSslCertificates, true);
IWebDriver driver = new RemoteWebDriver(capability);
// Set Chrome options.
ChromeOptions options = new ChromeOptions();
DesiredCapabilities dc = DesiredCapabilities.Chrome();
dc.SetCapability(ChromeOptions.Capability, options);
IWebDriver driver = new RemoteWebDriver(dc);
// Turn off the JavaScript Firefox
FirefoxProfileManager profileManager = new FirefoxProfileManager();
FirefoxProfile profile = profileManager.GetProfile("HARDDISKUSER");
profile.SetPreference("javascript.enabled", false);
IWebDriver driver = new FirefoxDriver(profile);
// Set the default page load timeout
driver.Manage().Timeouts().SetPageLoadTimeout(new TimeSpan(10));
// Start Firefox with plugins
FirefoxProfile profile = new FirefoxProfile();
profile.AddExtension(@"C:extensionsLocationextension.xpi");
IWebDriver driver = new FirefoxDriver(profile);
// Start Chrome with an unpacked extension
ChromeOptions options = new ChromeOptions();
options.AddArguments("load-extension=/pathTo/extension");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.SetCapability(ChromeOptions.Capability, options);
DesiredCapabilities dc = DesiredCapabilities.Chrome();
dc.SetCapability(ChromeOptions.Capability, options);
IWebDriver driver = new RemoteWebDriver(dc);
// Start Chrome with a packed extension
ChromeOptions options = new ChromeOptions();
options.AddExtension(Path.GetFullPath("localpathto/extension.crx"));
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.SetCapability(ChromeOptions.Capability, options);
DesiredCapabilities dc = DesiredCapabilities.Chrome();
dc.SetCapability(ChromeOptions.Capability, options);
IWebDriver driver = new RemoteWebDriver(dc);
// Change the default files’ save location
String downloadFolderPath = @"c:temp";
FirefoxProfile profile = new FirefoxProfile();
profile.SetPreference("browser.download.folderList", 2);
profile.SetPreference("browser.download.dir", downloadFolderPath);
profile.SetPreference("browser.download.manager.alertOnEXEOpen", false);
profile.SetPreference("browser.helperApps.neverAsk.saveToDisk", 
"application/msword, application/binary, application/ris, text/csv, image/png, application/pdf,
text/html, text/plain, application/zip, application/x-zip, application/x-zip-compressed, application/download, 
application/octet-stream");
this.driver = new FirefoxDriver(profile);

 

5) 사용법

참조 : https://hjjungdev.tistory.com/81?category=701177

private IWebDriver MakeDriver(string ip)
{
	ChromeOptions cOptions = new ChromeOptions();
	cOptions.AddArguments("disable-infobars");
	cOptions.AddArguments("--js-flags=--expose-gc");
	cOptions.AddArguments("--enable-precise-memory-info");
	cOptions.AddArguments("--disable-popup-blocking");
	cOptions.AddArguments("--disable-default-apps");
	cOptions.AddArguments("--headless");

	// 프록시 설정 Proxy proxy = new Proxy();
	proxy.Kind = ProxyKind.Manual;
	proxy.IsAutoDetect = false;
	proxy.HttpProxy = proxy.SslProxy = ip;
	cOptions.Proxy = proxy;
	cOptions.AddArgument("ignore-certificate-errors");

	ChromeDriverService chromeDriverService = ChromeDriverService.CreateDefaultService();
	chromeDriverService.HideCommandPromptWindow = true;

	IWebDriver driver = new ChromeDriver(chromeDriverService, cOptions);

	return driver;
}

 

 

반응형

Install 을 위한 셋업파일 만들기

C#
반응형

1. 기존 프로젝트의 솔루션 탐색기에서, 새 프로젝트 추가 > Setup Project 선택

* 없을 수 있으니 추가할 것

 

2. 설정

Setup Project 에서 기본출력 from XXX 더블 클릭.

  닷넷 선택 : InstallUrl 과 버전 입력

  셋업 프로젝트 > 오른쪽클릭 속성 > 구성관리자 > Prerequisites... > 닷넷 버전 고르기

  InstallUrl 은 필요한 버전 검색해서 수기 입력

  User's Deskop 선택후 오른쪽 화면에서 우클릭 + 추가 + ShortCut 으로 "바탕화면 바로가기" 만들기.

 

3. Icon Size 48 X 48

Application Folder 에 ICO 파일 추가후, "User's DeskTop"의 Short Cut 우 클릭에서 Ico 파일 선택 가능.

 

 

반응형

'C#' 카테고리의 다른 글

VisualStudioCode에서 개발을 위한 설정  (0) 2021.05.26
SQLite 설치  (0) 2017.12.26
실행시 관리자 권한창 띄우기  (0) 2017.07.26

Console Program, 자동 창 닫기 보류

C#/기타
반응형

1) Console.ReadLine();


2) Console.ReadKey();


3) 실행시 Ctrl + F5


4) System.Threading.Thread.Sleep(1000);

반응형

'C# > 기타' 카테고리의 다른 글

Socket Client/ Server 샘플 예제  (0) 2018.05.23
Audio Live Streaming  (0) 2018.05.23
디버깅시 코드에 브레이크 코드 넣기  (0) 2018.05.22

심각한 오류 발생 2.Audio File 만들면서 스트리밍

C#/Capturing Audio
반응형

- NetworkStream 이 Seekable 이 아니라서, 일단 Wav File 로 쓰면서 동시에 스트리밍시도.


- 그러나 읽기 권한 실패.


- 아무래도 CSCore 를 이용한 Net Streaming 은 포기해야 할듯.

반응형

심각한 문제점 발생. Seekable Stream

C#/Capturing Audio
반응형

- CSCore 에서 WaveWriter 의 파라미터로 스트림을 입력하는 것이 가능하다.


- 그래서 NetworkStream 을 입력해보았다.


- 그러나 NetworkStream 은 Seekable Stream 아니라서 오류가 발생함.

반응형

Socket Client/ Server 샘플 예제

C#/기타
반응형
// Server Socket
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// NameSpace 선언
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
 
namespace ServerSideSocket
{
  class ServerClass
  {
    public static Socket Server , Client;
     
    public static byte[] getByte = new byte[1024];
    public static byte[] setByte = new byte[1024];
     
    public const int sPort = 5000;
     
    [STAThread]
    static void Main(string[] args)
    {
      string stringbyte = null;
      IPAddress serverIP = IPAddress.Parse("127.0.0.1");
      IPEndPoint serverEndPoint = new IPEndPoint(serverIP,sPort);
       
      try
      {     
        Server= new Socket(
          AddressFamily.InterNetwork,
          SocketType.Stream,ProtocolType.Tcp);
           
        Server.Bind(serverEndPoint);
        Server.Listen(10);
 
        Console.WriteLine("------------------------");
        Console.WriteLine("클라이언트의 연결을 기다립니다. ");
        Console.WriteLine("------------------------");
                   
        Client = Server.Accept();
   
        if(Client.Connected)
        {
          while(true)
          {
            Client.Receive(getByte,0,getByte.Length,SocketFlags.None);
            stringbyte = Encoding.UTF7.GetString(getByte);
 
            if (stringbyte != String.Empty)
            {
              int getValueLength = 0;
              getValueLength = byteArrayDefrag(getByte);
               
              stringbyte = Encoding.UTF7.GetString(
                getByte,0,getValueLength+1);
 
              Console.WriteLine("수신데이터:{0} | 길이:{1}",
                stringbyte,getValueLength+1);
                 
              setByte = Encoding.UTF7.GetBytes(stringbyte);
              Client.Send(setByte,0,setByte.Length,SocketFlags.None);
            }
           
            getByte = new byte[1024];
            setByte = new byte[1024];
          }
        }
      }
        catch(System.Net.Sockets.SocketException socketEx)
      {
        Console.WriteLine("[Error]:{0}", socketEx.Message);
      }
      catch(System.Exception commonEx)
      {
        Console.WriteLine("[Error]:{0}", commonEx.Message);
      }
      finally
      {
        Server.Close();
        Client.Close();
      }
    }
     
    public static int byteArrayDefrag(byte[] sData)
    {
      int endLength = 0;
       
      for(int i = 0; i < sData.Length; i++)
      {
        if((byte)sData[i] != (byte)0)
        {
          endLength = i;
        }
      }
       
      return endLength;
    }
  }
}


// Client Socket
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
 
namespace ClientSideSocket
{
  class ClientClass
  {
    public static Socket socket;
    public static byte[] getbyte = new byte[1024];
    public static byte[] setbyte = new byte[1024];
 
    public const int sPort = 5000;
 
    [STAThread]
    static void Main(string[] args)
    {
      string sendstring = null;
      string getstring = null;
 
      IPAddress serverIP = IPAddress.Parse("127.0.0.1");
      IPEndPoint serverEndPoint = new IPEndPoint(serverIP,sPort);
 
      socket = new Socket(
        AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
         
      Console.WriteLine("------------------------------");
      Console.WriteLine(" 서버로 접속합니다.[엔터를 입력하세요] ");
      Console.WriteLine("------------------------------");
      Console.ReadLine();
 
      socket.Connect(serverEndPoint);
 
      if (socket.Connected)
      {
        Console.WriteLine(">>연결 되었습니다.(데이터를 입력하세요)");
      }
 
      while(true)
      {
        Console.Write(">>");
        sendstring = Console.ReadLine();
         
        if(sendstring != String.Empty)
        {
          int getValueLength = 0;
          setbyte = Encoding.UTF7.GetBytes(sendstring);
           
          socket.Send(setbyte,0,
            setbyte.Length,SocketFlags.None);
           
          Console.WriteLine("송신 데이터 : {0} | 길이{1}",
            sendstring, setbyte.Length);
             
          socket.Receive(getbyte,0,
            getbyte.Length,SocketFlags.None);
             
          getValueLength = byteArrayDefrag(getbyte);
           
          getstring = Encoding.UTF7.GetString(getbyte,
            0,getValueLength+1);
           
          Console.WriteLine(">>수신된 데이터 :{0} | 길이{1}",
            getstring , getValueLength+1);
        }
         
        getbyte = new byte[1024];
       }
    }
     
    public static int byteArrayDefrag(byte[] sData)
    {
      int endLength = 0;
       
      for(int i = 0; i < sData.Length; i++)
      {
        if((byte)sData[i] != (byte)0)
        {
          endLength = i;
        }
      }
       
      return endLength;
    }
  }
}



[출처] https://hooni.net/2382



반응형

'C# > 기타' 카테고리의 다른 글

Console Program, 자동 창 닫기 보류  (0) 2018.05.29
Audio Live Streaming  (0) 2018.05.23
디버깅시 코드에 브레이크 코드 넣기  (0) 2018.05.22

Audio Live Streaming

C#/기타
반응형

쉽게 되는 방법이 있군요.



반응형

'C# > 기타' 카테고리의 다른 글

Console Program, 자동 창 닫기 보류  (0) 2018.05.29
Socket Client/ Server 샘플 예제  (0) 2018.05.23
디버깅시 코드에 브레이크 코드 넣기  (0) 2018.05.22

디버깅시 코드에 브레이크 코드 넣기

C#/기타
반응형

System.Diagnostics.Debugger.Break();

반응형

'C# > 기타' 카테고리의 다른 글

Console Program, 자동 창 닫기 보류  (0) 2018.05.29
Socket Client/ Server 샘플 예제  (0) 2018.05.23
Audio Live Streaming  (0) 2018.05.23

Client IP 가져오기

C#/Capturing Audio
반응형

public static string getClientIp


{

    get

    {

        IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());

        string ClientIP = string.Empty;

        for (int i = 0; i < host.AddressList.Length; i++)

        {

            if (host.AddressList[i].AddressFamily == AddressFamily.InterNetwork)

            {

                ClientIP = host.AddressList[i].ToString();

            }

        }

        return ClientIP;

    }

}


....


private void Form1_Load()

{

String cip = getClientIp;

}


반응형