using System;
using System.IO;
using System.Net;
using System.Text;
public String ConvertImageURLToBase64(String ID)
{

            string url = "https://.../pictures/" + ID + "?key="special api key"";
            //create an object of StringBuilder type.
            StringBuilder _sb = new StringBuilder();
            //create a byte array that will hold the return value of the getImg method
            Byte[] _byte = this.GetImg(url);
            //appends the argument to the stringbulilder object (_sb)
            _sb.Append(Convert.ToBase64String(_byte, 0, _byte.Length));
            //return the complete and final url in a base64 format.
            return string.Format(@"data:image/jpg;base64, {0}", _sb.ToString());
            
}
private byte[] GetImg(string url)
{
            //create a stream object and initialize it to null
            Stream stream = null;
            //create a byte[] object. It serves as a buffer.
            byte[] buf;
            try
            {
                //Create a new WebProxy object.
                WebProxy myProxy = new WebProxy();
                //create a HttpWebRequest object and initialize it by passing the colleague api url to a create method.
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                //Create a HttpWebResponse object and initilize it
                HttpWebResponse response = (HttpWebResponse)req.GetResponse();
                //get the response stream
                stream = response.GetResponseStream();

                using (BinaryReader br = new BinaryReader(stream))
                {
                    //get the content length in integer
                    int len = (int)(response.ContentLength);
                    //Read bytes
                    buf = br.ReadBytes(len);
                    //close the binary reader
                    br.Close();
                }
                //close the stream object
                stream.Close();
                //close the response object 
                response.Close();
            }
            catch (Exception exp)
            {
                //set the buffer to null
                buf = null;
            }
            //return the buffer
            return (buf);
}

'공부방 > ASP.NET' 카테고리의 다른 글

IIS URL rewrite 모듈 설치 및 이용방법  (0) 2020.08.24

1. 설치

1.1. Manage nuget packages -> Browse [Newtonsoft.Json] 검색 -> Install

1.2. Nuget package manager -> Package Manager Console

PM> Install-Package Newtonsoft.Json

 

2. 사용명시

2.1. namespace등록

using Newtonsoft.Json.Linq;

 

3. 특징

2개의 Object를 사용

  • JObject : JSON Object
    • JObject 자체가 name값을 가질 수는 없습니다.
    • (key, value) pair 들을 가질 수 있습니다.
    • key : string 값입니다.
    • value : JToken 타입이며 대부분의 premitive type들과 DateTime, TiemSpan, Uri 값을 직접대입 가능하며, 기타 Object도 입력이 가능합니다.
      • value에 다른 JObject나, JArray를 넣을 수 있습니다.
  • JArray : JSON Array
    • JObject와 특징이 거의 비슷하나 key 없이 value 들을 가지고 있습니다.

즉, JObject나 Jarray 자체는 name을 가질 수 없으나, 다른 JObject에 value로 소속될 경우에는 key값을 가져야 하며, 다른 JArray에 소속될 경우에는 key값 없이 입력됩니다.

4. 사용법

4.1. JObject

생성

//생성 1 (공백)
var json = new JObject();

//생성 2 (JSON 형식의 문자열로 생성)
var json2 = JObject.Parse("{ id : \"Luna\" , name : \"Silver\" , age : 19 }");

//생성 3 (다른 class Object로부터 생성)
User u = new User { id = "SJ", name = "Philip", age = 25 };
var json3 = JObject.FromObject(u);

//생성 4 (무명형식으로 생성)
var json = JObject.FromObject(new { id = "J01", name = "June", age = 23 });

 

Element 추가

//.add(key, value)
var json = new JObject();
json.Add("id", "Luna");
json.Add("name", "Silver");
json.Add("age", 19);

//다른 JObject를 Element로 추가
var json2 = JObject.Parse("{ id : \"sjy\" , name : \"seok-joon\" , age : 27 }");
json2.Add("friend1", json);

//결과 형식
{
  "id": "sjy",
  "name": "seok-joon",
  "age": 27,
  "friend1": {
    "id": "Luna",
    "name": "Silver",
    "age": 19
  }
}
  

//JObject에 JArray 추가
var jFriends = new JArray();
jFriends.Add(json);
json2.Add("Friends", jFriends);
//결과 형식
{
  "id": "sjy",
  "name": "seok-joon",
  "age": 27,
    "friend1": {
    	"id": "Luna",
    	"name": "Silver",
    	"age": 19
  	},
  "Friends": [
  	{
  	  "id": "Luna",
  	  "name": "Silver",
  	  "age": 19
  	}
  ]
}

Element 사용

//var json_name = json["name"];
Console.WriteLine(json_name);
//Silver

Element 삭제

//.Remove(key)
json.Remove("name");
Console.WriteLine(json.ToString());

//결과
{
  "id": "Luna",
  "age": 19
}

//.RemoveAll() 모든 Element 삭제
json5.RemoveAll();
Console.WriteLine(json5.ToString());

//결과
{}

 

4.2. JArray (Element 입력시 key를 가지지 않는 다는 것을 빼고는 JObject와 거의 흡사)

Element 추가

// .Add(value);
var jarray = new JArray();
jarray.Add(1);
jarray.Add("Luna");
jarray.Add(DateTime.Now);

// JObject를 Element로 추가
var jFriends = new JArray();
jFriends.Add(json);

// JArray를 Element로 추가
var jarray2 = new JArray();
jarray2.Add(jarray);
jarray2.Add(jFriends);

Element 사용

var jf0 = jFriends[0];

//for, foreach 활용
foreach(JObject fElement in jFriends)
{
    var fName = fElement["name"] ?? "<NULL>";
    Console.WriteLine(fName);
}

Element 삭제

jFriends.Remove(jFriends[1]);

 

참고글 : devstarsj.github.io/development/2016/06/11/CSharp.NewtonJSON/

1. URL Rewrite(URL 재작성) 설치

URL 재작성을 사용하기 위해서는 웹 플랫폼 인스톨러를 통해서 URL 재작성 기능을 설치해야 합니다.
다운로드 : 
Web Platform Installer

웹 플랫폼 인스톨러에서 URL 재작성 기능을 검색

URL 재작성 2.0 추가 -> 설치(I) 진행

IIS 관리자에서 웹사이트를 선택 IIS기능 목록에 'URL 재작성' 메뉴가 있으면 설치 성공

 

2. 이용 방법

추가 1. ASP.NET_SessionId 쿠키 SameSite=None; Secure 옵션 지정
추가 2. HTTPS 리다이렉트 rule

<?xml version="1.0" encoding="utf-8"?>
<configuration>
	<system.webServer>
    	  <!--Chrome 80업데이트 Session Cookie SameSite=None; Secure 옵션 이슈로 rewrite-'AddSameSiteCookieHttps' rule 추가 1-->
	      <rewrite> <!--VS2010에서는 잘못된 자식요소로 인식--> 
	        <outboundRules> 
	          <rule name="AddSameSiteCookieHttps" preCondition="Https" enabled="true" stopProcessing="true"> 
	            <match serverVariable="RESPONSE_Set-Cookie" pattern="^(.*)(ASP\.NET_SessionId)(=)(.*)$" /> 
	            <action type="Rewrite" value="{R:0}; SameSite=None; Secure" /> 
	          </rule> 
	          <preConditions> 
	            <preCondition name="Https"> 
	              <add input="{HTTPS}" pattern="^ON$" /> 
	              <add input="{HTTP_USER_AGENT}" pattern="iphone|ipad|ipod" negate="true" /> 
	            </preCondition> 
	          </preConditions> 
	        </outboundRules>
            <!--Session Cookie Secure 옵션 이슈로 'RedirectHTTPtoHTTPS' rule 추가 2-->
	        <rules> 
	          <rule name="RedirectHTTPtoHTTPS" stopProcessing="true"> 
	            <match url="(.*)"/> 
	            <conditions> 
	              <add input="{HTTPS}" pattern="^OFF$"/> 
	            </conditions> 
	            <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="SeeOther"/> 
	          </rule> 
	        </rules> 
	      </rewrite>
	</system.webServer>
</configuration>



 

'공부방 > ASP.NET' 카테고리의 다른 글

Convert Image URL to base 64 function  (0) 2020.09.09

VM setting Network : Bridged 확인 후 On

1. CentOS7 설치

2. 네트워크 설정 (ftp, PuTTy접속)

더보기

#vi /etc/sysconfig/network-scripts/ifcfg-네트워크ID

확인사항)
HWADDR=00:00:00:00:00:00 
TYPE=Ethernet 
BOOTPROTO=dhcp 
DEFROUTE=yes 
PEERDNS=yes 
PEERROUTES=yes 
IPV4_FAILURE_FATAL=no 
IPV6INIT=yes 
IPV6_AUTOCONF=yes 
IPV6_DEFROUTE=yes 
IPV6_PEERDNS=yes 
IPV6_PEERROUTES=yes 
IPV6_FAILURE_FATAL=no 
NAME=eno16777736 
UUID=11111111-1111-1111-1111-111111111111 
ONBOOT=yes 
GETEWAY=192.168.0.1 
DNS1=168.126.63.1 

 

기본 프로그램 설치 및 업데이트

더보기


#yum -y update
#yum -y install ftp
#yum -y install net-tools

3. httpd (apache)설치

더보기

vsftpd 설치
# yum -y install vsftpd

부팅시 vsftpd 자동시작
# systemctl enable vsftpd.service

vsftpd 서비스 시작
# systemctl start vsftpd

 

더보기

방화벽 설치
# yum -y install system-config-firewall-tui

방화벽 포트허용 설정
# vi /etc/sysconfig/iptables 
  
-A INPUT -p tcp -m state --state NEW -m tcp --dport 80 -j ACCEPT 
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT 
-A INPUT -p tcp -m state --state NEW -m tcp --dport 21 -j ACCEPT 
-A INPUT -p tcp -m state --state NEW -m tcp --dport 3306 -j ACCEPT 

※Tip
포트 80 : 아파치    
포트 22 : SSH     
포트 21 : FTP     
포트 3306 : MySql 

더보기

방화벽 데몬 Disable 
# systemctl mask firewalld 

방화벽 시작 
# systemctl start iptables 
  
부팅시 자동 시작 
# systemctl enable iptables.service

 

Apache 설치

더보기

아파치 설치
# yum -y install httpd

부팅시 자동시작
# systemctl enable httpd.service
 
아파치 서버 시작
# systemctl start httpd

 

4. PHP 설치

Google

5. Mysql(mariaDB)설치 및 세팅

Google

DB생성, 계정 생성, 권한부여

6. 재부팅

더보기

#shutdown -r now

 

7. 그누보드 업로드 및 설정진행

그누보드 다운로드
https://sir.kr/main/g5/

설정진행 중 chmod 707 data 요청 계속나올때※

Tip. CentOS SELINUX 설정

더보기

//SELinux 확인
#getsebool -a | grep httpd 

//SELinux 변경
#setsebool -P httpd_can_network_connect=on
#setsebool -P httpd_can_network_connect_db=on
#setsebool -P allow_httpd_anon_write=1 
#setsebool -P allow_httpd_sys_script_anon_write=1 


#chcon -R -t httpd_sys_rw_content_t /var/www/html

 

8. 아미나 업로드

아미나 다운로드

http://amina.co.kr/bbs/board.php?bo_table=apms 

 

'공부방 > Issue' 카테고리의 다른 글

기술적 부채  (0) 2020.05.20
복구파티션 삭제  (0) 2020.05.07
VMware 용량추가  (0) 2020.05.07
Crystal Reports Date format  (0) 2020.04.28
EditPlus 설정 파일 경로  (0) 2020.04.27


-- ※ #지역테이블 ##전역테이블
-- ※ Table Name : PgTid

--이전 임시테이블 존재시 삭제
IF OBJECT_ID('tempdb..#PGTid') IS NOT NULL DROP TABLE #PGTid

--임시테이블 생성
Create Table #PGTid(
Tid nvarchar(40)
)

--임시테이블 INSERT
INSERT INTO #PGTid(Tid)Values('')

--임시테이블 활용 작업 Start
Select * From #PGTid
--임시테이블 활용 작업 End

--사용 후 임시테이블 삭제
IF OBJECT_ID('tempdb..#PGTid') IS NOT NULL DROP TABLE #PGTid

'공부방 > MSSQl' 카테고리의 다른 글

구동중인 SP확인 및 종료  (0) 2020.06.15
ViewTable [Cols]  (0) 2020.06.03
DB 백업 및 리스토어 명령어  (0) 2020.06.03
MsSql - DATE - CONVERT  (0) 2020.04.22

구동중인 process 확인

select * from sys.sysprocesses

 

sp 텍스트로 확인

sp_helptext 'sp_who'

 

해당 sp 정보확인

sp_who 65

sp_who 'active'

 

클라이언트에서 MSSQL로 보낸 최종 명령문을 표시한다.

dbcc inputbuffer(65)

 

 해당 프로세스를 킬

 kill65

'공부방 > MSSQl' 카테고리의 다른 글

임시테이블 활용  (0) 2020.06.19
ViewTable [Cols]  (0) 2020.06.03
DB 백업 및 리스토어 명령어  (0) 2020.06.03
MsSql - DATE - CONVERT  (0) 2020.04.22

.assert(조건문,{})

for(let number = 0; number <= 5; number += 1){
    console.log('the is ' + number);
    console.assert(number !== 3, {number: number, errorMsg: 'the is ' + number});
}

assert result

.count(name)

function countName(name){
	console.count(name)
}
countName('a');
countName('a');
countName('b');
countName('a');
countName('c');

count result

※ console.countReset(name) 으로 누적된 카운트 초기화 가능 합니다.

 

.log() / .info() / .debug() / .warn() / .error()

log / info / debug / warn / error result

debug는 로그레벨이 debug로 설정되어야 확인 가능 합니다. (※ 일부 브라우저로 제한)

 

.group(), groupEnd()

console.log("그룹 없는 로그");
console.group("첫번째 그룹");
console.log("첫번째 그룹의 로그");
console.group("두번째 그룹");
console.log("두번째 그룹의 로그");
console.groupEnd();
console.log("첫번째 그룹의 로그2");
console.groupEnd();
console.log("그룹없는 로그");

group(), groupEnd() result

.profile(), profileEnd()

어떤 로직에서 리소스를 많이 사용하는지 등을 체크하는 용도로 사용 가능 합니다.

※ 브라우저마다 호환성이 다릅니다.

 

.table()

데이터를 테이블화 하여 출력해주는 메소드

console.table(['사과', '수박', '참외']);
console.table([['사과', '수박', '참외'], ["자두","옥수수","멜론"]]);
console.table([
    {name: "apple", value:"iphone"},
    {name: "samsung", value:"galaxy"},
    {name: "google", value:"pixel"}
]);

 

.time(), timeEnd(), timeLog()

console.time('execute time: for loop');
for (var i=0; i<1000000; i++) {
    if (i === 100000) {console.timeLog('execute time: for loop');}
}
console.timeEnd('execute time: for loop');

time, timeLog, timeEnd result

 

.trace()

function func1() {
    func2();
}
function func2() {
    console.trace();
}

func1();

trace result

trace()메소드가 호출된 이전 시점에 호출된 함수들을 파악 할 수 있습니다.

 

.dir

DOM객체의 메서드를 확인하고 싶을때사용

console.log(document.body);
console.dir(document.body);


function f() { return true; }
console.log(f);
console.dir(f);

 

 

+ Recent posts