먹는게 남는거다!

ASP.NET Request QueryString encoding

C#, ASP.NET
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
private System.Collections.Generic.Dictionary<stringstring> requestDic;
 
protected void Page_Load(object sender, EventArgs e)
{
    ParseRequestQueryStringData(System.Text.Encoding.GetEncoding(949));
 
    string t = GetRequestQueryString("strErrMsg");
    lbMessage.Text = t;
}
 
private void ParseRequestQueryStringData(System.Text.Encoding encoding)
{
    string url = HttpUtility.UrlDecode(Request.RawUrl, encoding);
    int s = url.IndexOf('?'0);
    if (s < 0)
    {
        return;
    }
 
    requestDic = new System.Collections.Generic.Dictionary<stringstring>();
    string requestData = "&" + url.Substring(s + 1+ "&";
 
    int pos = requestData.IndexOf('&'0);
    int pos2 = 0;
 
    string paramName;
    string paramValue;
 
    while (pos >= 0 && pos2 >= 0)
    {
        pos2 = requestData.IndexOf('=', pos);
 
        if (pos2 > 0)
        {
            paramName = requestData.Substring(pos + 1, pos2 - pos - 1);
 
            pos = requestData.IndexOf('&', pos2);
 
            if (pos > 0)
            {
                paramValue = requestData.Substring(pos2 + 1, pos - pos2 - 1);
                requestDic.Add(paramName, paramValue);
            }
        }
    }
}
 
private string GetRequestQueryString(string paramName)
{
    try
    {
        return requestDic[paramName];
    }
    catch (System.Collections.Generic.KeyNotFoundException keyEx)
    {
        return null;
    }
}
cs

 

ASP.NET Request Form encoding

C#, ASP.NET
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
private static Dictionary<stringstring> GetEncodedForm(System.IO.Stream stream, System.Text.Encoding encoding)
{
    System.IO.StreamReader reader = new System.IO.StreamReader(stream, System.Text.Encoding.ASCII);
    return GetEncodedForm(reader.ReadToEnd(), encoding);
}
 
private static Dictionary<stringstring> GetEncodedForm(string urlEncoded, System.Text.Encoding encoding)
{
    Dictionary<stringstring> form = new Dictionary<stringstring>();
    string[] pairs = urlEncoded.Split("&".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
 
    foreach (string pair in pairs)
    {
        string[] pairItems = pair.Split("=".ToCharArray(), 2, StringSplitOptions.RemoveEmptyEntries);
        string name = HttpUtility.UrlDecode(pairItems[0], encoding);
        string value = (pairItems.Length > 1) ? HttpUtility.UrlDecode(pairItems[1], encoding) : null;
        form.Add(name, value);
    }
    return form;
}
cs

 

출처: https://stackoverflow.com/questions/1012120/iso-8859-1-to-utf8-in-asp-net-2

[C#] EPPlus로 엑셀 생성 시 필요없는 property 제거하기

C#, ASP.NET

EPPlus를 이용하여 POCO 클래스를 excel 파일에 출력할 때

Attribute를 이용하여 특정 property를 제외하는 방법



Attribute


1
public class EpplusIgnore : Attribute { }
cs



Epplus extensions


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public static class Extensions
{
    public static ExcelRangeBase LoadFromCollectionFiltered<T>(this ExcelRangeBase @this, IEnumerable<T> collection) 
where T:class
    {
        MemberInfo[] membersToInclude = typeof(T)
            .GetProperties(BindingFlags.Instance | BindingFlags.Public)
            .Where(p=>!Attribute.IsDefined(p,typeof(EpplusIgnore)))
            .ToArray();
 
        return @this.LoadFromCollection<T>(collection, false
            OfficeOpenXml.Table.TableStyles.None, 
            BindingFlags.Instance | BindingFlags.Public, 
            membersToInclude);
    }
 
}
cs



Sample 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Person
{
    [EpplusIgnore]
    public int Key { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}
 
class Program
{
    static void Main(string[] args)
    {
        var demoData = new List<Person> { 
new Person { Key = 1, Age = 40, Name = "Fred" }, 
new Person { Key = 2, Name = "Eve", Age = 21 } 
};
 
        FileInfo fInfo = new FileInfo(@"C:\Temp\Book1.xlsx");
        using (var excel = new ExcelPackage())
        {
            var ws = excel.Workbook.Worksheets.Add("People");
            ws.Cells[11].LoadFromCollectionFiltered(demoData);
 
            excel.SaveAs(fInfo);
        }
    }
}
cs



출처: https://entityframework.net/knowledge-base/25603492/ignoring-properties-when-calling-loadfromcollection-in-epplus



PushSharp로 APNs 이용중 오류 해결 - 패키지에 제공된 자격 증명을 인식할 수 없습니다

C#, ASP.NET

System.ComponentModel.Win32Exception: 패키지에 제공된 자격 증명을 인식할 없습니다


PushSharp.Apple.ApnsNotificationException: Apns notification error: 'ConnectionError' ---> System.ComponentModel.Win32Exception: 패키지에 제공된 자격 증명을 인식할 수 없습니다

   위치: System.Net.SSPIWrapper.AcquireCredentialsHandle(SSPIInterface SecModule, String package, CredentialUse intent, SecureCredential scc)

   위치: System.Net.Security.SecureChannel.AcquireCredentialsHandle(CredentialUse credUsage, SecureCredential& secureCredential)

   위치: System.Net.Security.SecureChannel.AcquireClientCredentials(Byte[]& thumbPrint)

   위치: System.Net.Security.SecureChannel.GenerateToken(Byte[] input, Int32 offset, Int32 count, Byte[]& output)

   위치: System.Net.Security.SecureChannel.NextMessage(Byte[] incoming, Int32 offset, Int32 count)

   위치: System.Net.Security.SslState.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)

   위치: System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)

   위치: System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)

   위치: System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)

   위치: System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)

   위치: System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)

   위치: System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)

   위치: System.Net.Security.SslState.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)

   위치: System.Net.Security.SslState.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)

   위치: System.Net.Security.SslState.ForceAuthentication(Boolean receiveFirst, Byte[] buffer, AsyncProtocolRequest asyncRequest)

   위치: System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)

   위치: PushSharp.Apple.ApnsConnection.<connect>d__25.MoveNext()

--- 예외가 throw된 이전 위치의 스택 추적 끝 ---

   위치: System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

   위치: System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

   위치: PushSharp.Apple.ApnsConnection.<SendBatch>d__21.MoveNext()

   --- 내부 예외 스택 추적의 끝 ---

   위치: PushSharp.Apple.ApnsServiceConnection.<Send>d__2.MoveNext()



PushSharp을 이용해서 iOS 기기에 푸시를 보낼 때 위와 같은 오류가 발생했습니다.


apple에서 발급 받은 인증서 권한 문제로 보여 구글링을 해보면 다양한 해법이 있습니다.


그 중 대부분이 apple에서 인증서를 발급 받을 때 private만 추출해야 하는데 다 추출해서 발생한 문제입니다.



저 같은 경우는 로컬 컴퓨터에서 테스트시 정상 발송되었기 때문에 인증서 문제는 아니었습니다.


제가 성공한 방법은 PushSharp 샘플처럼 인증서 파일을 직접 사용하는 것이 아니라 저장소에 인증서를 등록하고 불러와서 사용하는 방법입니다.


저장소에 등록한 인증서를 지문(THUMBPRINT)를 통해 가져오는 코드는 아래와 같습니다.



1
2
3
4
5
6
7
8
string thumbprint = "YOUR THUMBPRINT";
var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
var certificate = store.Certificates.Find(
    X509FindType.FindByThumbprint, thumbprint, validOnly: false)
    .Cast<X509Certificate2>().SingleOrDefault();
var apnsConfig = new ApnsConfiguration(
    ApnsConfiguration.ApnsServerEnvironment.Production, certificate);
cs


출처: https://stackoverflow.com/questions/23329040/pushsharp-apns-production-the-credentials-supplied-to-the-package-were-not-reco



전 인증서를 로컬 컴퓨터에 저장하였기 때문에 위 코드에서 StoreLocation.CurrentUserStoreLocation.LocalMachine 으로 변경하였습니다.


지문(THUMBPRINT)는 인증서를 더블 클릭 후 나오는 인증서창의 자세히탭에서 확인할 수 있습니다.

(단, thumbprint 변수에 지문을 넣을 때는 공백 없이 입력해야 합니다.)

  

 

 

 


[크롬북으로 개발하기] 원격접속시 텔레그램 메시지 받기 : 5. 전송 프로그램 만들기 (C#)

C#, ASP.NET

드디어 모든 개발 환경이 구축되었기 때문에 본격적인 개발을 시작하려 합니다.

사실 개발할 프로그램은 단순합니다. 입력받은 메시지를 텔레그램봇에게 전송하는 것이 전부입니다.


소스도 정말 간단해서 기본 콘솔 프로그램 클래스와 텔레그램 전송 클래스만으로 구성되어 있습니다.

텔레그램 메시지 전송 클래스 (\src\TelegramBot.cs)

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
98
99
100
101
102
103
104
105
using System;
using System.Net;
using System.Net.Cache;
using System.Text;
using System.IO;
 
public class TelegramBot
{
    private static readonly string _baseUrl = "https://api.telegram.org/bot";
    private static readonly string _token = "xxxxxxxxx:xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
    private static readonly string _chatId = "xxxxxxxx";
 
    /// <summary>
    /// 텔레그램봇에게 메시지를 보냅니다.
    /// </summary>
    /// <param name="text">보낼 메시지</param>
    /// <param name="errorMessage">오류 메시지</param>
    /// <returns>결과</returns>
    public static bool SendMessage(string text, out string errorMessage)
    {
        return SendMessage(_chatId, text, out errorMessage);
    }
    
    /// <summary>
    /// 텔레그램봇에게 메시지를 보냅니다.
    /// </summary>
    /// <param name="chatId">chat id</param>
    /// <param name="text">보낼 메시지</param>
    /// <param name="errorMessage">오류 메시지</param>
    /// <returns>결과</returns>
    public static bool SendMessage(string chatId, string text, out string errorMessage)
    {
        string url = string.Format("{0}{1}/sendMessage", _baseUrl, _token);
        
        HttpWebRequest req = WebRequest.Create(new Uri(url)) as HttpWebRequest;
        req.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
        req.Timeout = 30 * 1000;        
        req.Method = "POST";
        req.ContentType = "application/json";
 
        string json = String.Format("{{\"chat_id\":\"{0}\", \"text\":\"{1}\"}}", chatId, EncodeJsonChars(text));
        byte[] data = UTF8Encoding.UTF8.GetBytes(json);
        req.ContentLength = data.Length;
        using (Stream stream = req.GetRequestStream())
        {
            stream.Write(data, 0, data.Length);
            stream.Flush();
        }
 
        HttpWebResponse httpResponse = null;
        try
        {
            httpResponse = req.GetResponse() as HttpWebResponse;
            if (httpResponse.StatusCode == HttpStatusCode.OK)
            {
                string responseData = null;
                using (Stream responseStream = httpResponse.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(responseStream, UTF8Encoding.UTF8))
                    {
                        responseData = reader.ReadToEnd();
                    }
                }
                
                if (0 < responseData.IndexOf("\"ok\":true"))
                {
                    errorMessage = String.Empty;
                    return true;
                }
                else
                {
                    errorMessage = String.Format("결과 json 파싱 오류 ({0})", responseData);
                    return false;
                }
            }
            else
            {
                errorMessage = String.Format("Http status: {0}", httpResponse.StatusCode);
                return false;
            }
        }
        catch (Exception ex)
        {
            errorMessage = ex.Message;
            return false;
        }
        finally
        {
            if (httpResponse != null)
                httpResponse.Close();
        }
    }
    
    private static string EncodeJsonChars(string text)
    {
        return text.Replace("\b""\\\b")
            .Replace("\f""\\\f")
            .Replace("\n""\\\n")
            .Replace("\r""\\\r")
            .Replace("\t""\\\t")
            .Replace("\"""\\\"")
            .Replace("\\", "\\\\");
    }
}
    
cs


텔레그램에서 제공하는 Web api를 호출하는 것이 주 내용입니다.

위 코드 중에서 _token, _chatId는 이전 포스트([크롬북으로 개발하기] 원격접속시 텔레그램 메시지 받기 : 2. 텔레그램봇 생성하기)에서 발급받은 token과 chat id를 입력하시면 됩니다.

콘솔 프로그램 클래스 (\src\main.cs)

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
using System;
using System.Collections.Generic;
 
public class RemoteAlert 
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Telegram Remote Alert v0.1\n\n");
        
        if (args.Length == 0)
        {
            Console.WriteLine("사용 예) TelegramRemoteAlert.exe \"보낼 내용\"");
            return;
        }
        
        string text = args[0];
        string errorMessage = null;
        bool ret = TelegramBot.SendMessage(text, out errorMessage);
        
        if (ret)
            Console.WriteLine(String.Format("발송: {0}", text));
        else
            Console.WriteLine(String.Format("오류: {0}", errorMessage));
    }
}
cs


위의 코드를 컴파일 후 cmd 창에서 아래와 같이 입력하면 메시지가 전송되는 것을 확인할 수 있습니다.


실행파일.exe "보낼 메시지"



위 화면은 cloud ide인 goorm.io에서 컴파일 후 실행한 모습입니다.

"발송: 메시지 왔숑! 메시지 왔숑!"에서 메시지가 성공적으로 발송된 것을 알 수 있습니다.



이제 해당 프로그램을 윈도우 시작 프로그램에 등록만 해주면 윈도우 시작 때마다

텔레그램으로 메시지를 받을 수 있습니다.


- 끝 -


[크롬북으로 개발하기] 원격접속시 텔레그램 메시지 받기 : 4. Cloud IDE로 개발하기 (goorm.io)

C#, ASP.NET

크롬북으로 개발하기로 맘먹고 여러 개발 툴을 찾아봤습니다. CaretZed Code Editor 등 괜찮은 에디터들이 있었지만 Visual Studio의 막강한 기능에 익숙해진 저에게 해당 에디터들은 2% 부족했습니다.

그래서 크롬북을 리눅스로 변경해서 MonoDevelop이나 Visual Studio Code를 사용할까 하다가 순수 크롬북만으로 개발하는 것이 목적이기 때문에 대안을 찾던 중 cloud ide라는 것을 알게 되었습니다.


Cloud ide는 웹브라우저만 있으면 어디서든 코드 편집, 빌드, 디버깅까지 clipse나 Visual Studio 못지않은 통합 개발 환경을 제공하는 웹솔루션입니다.


그중에서 유명한 Cloud9을 둘러봤지만 아쉽게도 C#으로 개발하기 위해서는 별도 템플릿을 설치해야 하는 번거로움이 있어서 다른 cloud ide를 찾던 중 goorm.io이라는 웹사이트를 알게 되었습니다.



국내 회사에서 개발하여 한글 지원도 잘 되고 무엇보다 별도 세팅 없이 C#뿐만 아니라 node.js, PHP, JAVA, Ruby 등 다양한 언어를 지원하며 온라인상에서 컴파일뿐만 아니라 디버깅도 지원합니다.

더구나 512MB 메모리, 5GB 스토리지를 무료로 제공하기 때문에 비용 걱정도 없습니다.


회원 가입 후, 우측 상단의 "새 컨테이너 생성" 버튼을 클릭하면 위와 같이 컨테이너 생성 팝업이 나옵니다.

적당한 이름을 입력하고 언어를 생성하면 아래와 같이 컨테이너가 생성됩니다.


컨테이너를 생성한 후, 좌측 아래 "실행" 버튼을 클릭하면 아래와 같이 우리에게 익숙한 IDE 화면이 나옵니다.

지금이야 무덤덤하지만 처음 아래 화면을 봤을 때 무거운 IDE를 온라인상에서 구현한 모습에 적잖은 충격이었습니다.

이제 본격적인 개발을 시작해 보려고 합니다.

우선 "파일" -> "새로 만들기" -> "SCM" 메뉴를 클릭합니다.

아래와 같이 "새 프로젝트" 팝업이 나오면 저장소 URL에 지난번에 생성한 gitlab.com repository 주소를 입력하고 인증 항목에 유저 아이디, 패스워드를 입력합니다.

유형: Git
저장소 URL: gitlab.com에서 생성한 repository 주소 (https://gitlab.com/xxx/xxxx.git)
리버전: HEAD
인증: 인증된 사용자
유저: gitlab.com 회원 아이디
패스워드: gitlab.com 비밀번호


위와 같이 프로젝트 상세 정보를 입력하면 gitlab.com repository에서 소스 파일들을 가져오게 됩니다.






이제 C# 콘솔 프로그램 설정을 해야 합니다.

위의 이미지와 같이 프로젝트 속성창을 연 후, .NET 패널에 아래와 같이 설정값을 입력합니다.

메인 이름: main
소스 경로: src/
빌드 경로: bin/

이렇게 설정하면 콘솔 프로그램 실행시 /src/main.cs 파일이 진입점이 됩니다.

따라서 마지막으로 아래 이미지와 같이 /src, /bin 폴더와 /src/main.cs 파일을 생성해야 합니다.




이제 /src/main.cs 파일에 열심히 작업하면 됩니다.


- 끝 - 





[크롬북으로 개발하기] 원격접속시 텔레그램 메시지 받기 : 3. 소스 관리하기 (gitlab.com)

C#, ASP.NET

몇 줄 안되는 소스지만 그래도 관리가 필요할 것 같아 대세인 github에 repository를 생성하려 했습니다.

그런데 아쉽게도 github는 비공개시 유료라 대체재를 찾던중 gitlab.com 을 알게 되었습니다.

사실 검색중에 알게된 Bitbucket이 더 기능도 많고 좋아 보였지만 귀찮아서 이번에는 gitlab.com을 이용해 볼려고 합니다.
(다음에 기회에 되면 Bitbucket에 대해 포스팅 해보겠습니다.)




gitlab.com은 Community Edition과 Enterprise Edition, 무료 호스팅 버전을 제공하는 매우 고마운 사이트입니다.


gitlab.com Compare 웹페이지에서 두 Edition의 차이를 비교해 보면 알 수 있듯이 Community Edition도 사용하는데 충분한 기능을 제공하고 있습니다.

하지만 ...

Community Edition은 설치를 해야 하고 그에 따라 관리도 해야 하기 때문에 무료 호스팅을 이용하기로 결정했습니다.


1. 계정 생성




gitlab.com은 Google Plus, Twitter 등의 소셜 로그인과 일반 회원 가입을 통한 로그인을 모두 지원합니다.

우선 이름, 회원 아이디 등을 입력하고 "Sign up" 버튼을 클릭하여 회원 계정을 생성합니다.

그 다음 "Almost there..."라는 웹페이지에서 "Request new confirmationemail" 버튼을 클릭하면 회원 가입시 입력한 이메일로 계정 확인 이메일이 도착합니다.

해당 이메일의 "Confirm your account" 버튼을 클릭하면 비로소 회원 가입이 완료 됩니다.



2. 프로젝트 생성


회원 가입 후 처음 로그인을 하면 생성된 프로젝트가 없기 때문에 위와 같이 심심한 웹페이지를 만나게 됩니다.

이제 "New project"를 클릭하여 새로운 프로젝트를 생성합니다.




당황스러울 정도로 프로젝트 생성이 간단합니다.

프로젝트 설명, 프로젝트 가져오기 등의 옵션이 있지만 특별한 설정 없이 프로젝트 이름만 입력해도 됩니다.

물론 부끄러운 소스를 감추기 위해 Visibility Level은 Private로 설정하였습니다.




- 끝 -



[크롬북으로 개발하기] 원격접속시 텔레그램 메시지 받기 : 2. 텔레그램봇 생성하기

C#, ASP.NET

텔레그램으로 메시지를 받기 위해서는 BotFather라는 봇에게 텔레그램봇 생성을 요청해야 합니다.

@botfather라는 봇을 검색 후 "시작" 또는 "재시작" 버튼을 클릭하여 BotFather와 대화를 시작합니다.



우선 "/newbot"을 입력하여 봇을 생성하고 싶다고 말합니다.

그 후에 생성할 봇의 이름을 입력하고 마지막으로 봇이 사용할 username을 입력하면 끝입니다.
(username은 bot 이라는 단어로 끝나야 합니다.)

그럼 BotFather는 새로운 봇을 생성하고 위와 같이 token을 알려줍니다.
("Use this token to access the HTTP API:" 밑에 있는 문자열이 token입니다.)

이 토큰을 별도로 적어 놓습니다. 

주의할 점은 이 토큰은 일종의 비밀번호이기 때문에 유출되면 안됩니다.



이제 생성된 봇에게 나의 존재를 알리는 작업이 필요합니다.

우선 위 이미지의 생성된 봇 링크(예: telegram.me/AlertMe2Bot)를 클릭하여 대화를 시작합니다.


그리고 생성한 텔레그램봇이 내 chat id를 인식할 수 있도록 어떤 메시지든 입력합니다.




이제 마지막 작업입니다.

생성된 봇이 인지한 내 chat id를 찾는 일만 남았습니다.

웹브라우져를 연 후 https://api.telegram.org/bot[아까 발급 받은 token]/getUpdates 를 입력합니다.

그럼 위와 같이 생성된 봇에게 입력했던 메시지 정보가 나옵니다.


{"ok":true,"result":[{"update_id":413816513, "message":{"message_id":2,"from":{"id":434650172,"first_name":"\uc2b9\uc900","last_name":"\uc774","username":"test"},"chat":{"id":45810672,"first_name":"\uc2b9\uc800","last_name":"\uc674","username":"test2","type":"private"},"date":1467868645,"text":"\uc2dc\uc791"}}]}


이 중에 빨간 id 부분이 내 chat id 입니다.

이 chat id를 이용하면 텔레그램봇이 나에게 메시지를 보낼 수 있습니다.

그러므로 이것도 별도로 적어 놓습니다.



이제 진짜 마지막 작업입니다. ^^;

Fiddler를 통해 실제로 봇에게 메시지를 보내 봅니다.


METHOD: POST

URL: https://api.telegram.org/bot[아까 발급 받은 token]/sendMessage
Content-Type: application/json
Request Body: {"chat_id": "[내 chat id]", "text": "진짜 끝!"}


위와 같이 텔레그램 봇에 메시지를 전송하면 아래와 같이 내 텔레그램으로 메시지가 옵니다. 


이젠 정말 완전 끝!

수고하셨습니다.



[크롬북으로 개발하기] 원격접속시 텔레그램 메시지 받기 : 1. 시작하기

C#, ASP.NET

지난 달에 크롬북을 구입하여 이런 저런 기능들을 배우며 잘 쓰고 있지만 가끔 MS Windows가 그리울 때가 있습니다.

물론 집 PC를 이용해도 되지만 다른 방법이 없을지 찾아보던 중 "크롬북에서 AWS를 활용해 윈도우 사용하기 (1/2 - 설정 편)"이라는 블로그 포스팅을 찾게 되었습니다.


아마존에서 제공하는 AWS(Amazon Web Services)를 이용하여 가상 MS Windows 를 만드는 것입니다.

글쓴이가 설정법을 쉽게 설명해 주셔서 차근차근 따라하니 금방 가상 Windows를 만들 수 있었습니다.

비록 1년 뒤에는 유료지만 그 때까지는 필요할 때 요긴하게 쓸것 같습니다.



하지만 ...

추측하기 어렵게 숫자, 영문자, 특수문자까지 조합하여 비밀번호를 만들어도 IP만 알면 누구나 접근할 수 있기에 보안상 불안 했습니다.

그래서 접속을 막을 수는 없겠지만 접속하면 바로 알 수 있는 방법이 없을까 생각 중 텔레그램봇 기능이 생각났습니다.

이제부터 원격접속시 저에게 텔레그램 메시지를 발송하는 텔레그램봇을 만들어 볼까 합니다.