본문 바로가기
C#/Firebase

C# : Firebase 사용하기 - 02 (Firebase 연동)

by Half-Dev 2021. 1. 1.

 

안녕하세요.

하프개발자 입니다.

 

저번에 이어서 바로 진행을 해보도록 하겠습니다.

 

Part 1. 패키지 설치

패키지 Google.Cloud.Firestore를 설치해주도록 합시다.

다운로드 하는데 시간이 좀 걸립니다.

 

프로젝트를 선택하신 뒤 추가 -> 기존 항목으로 진행해줍니다.

 

1편에서 중요하다고 했었던 비공개 키를 가져오도록 합니다.

 

가져온 비공개 키를 클릭 후 빌드 작업은 내용으로, 출력 디렉터리에 복사는 항상 복사로 설정을 해줍니다.

 

 

Part 2. Firebase 연동

이제 본격적으로 연동을 시작하겠습니다.

우선 Google.Cloud.FireStore를 추가해주도록 합니다.

1
using Google.Cloud.Firestore;
cs

 

추가적으로 FirestoreDB 전역변수를 선언해주도록 합니다.

1
FirestoreDb db;
cs

 

Form1_Load 에다가 추가적인 코드를 작성하겠습니다.

아래의 코드는 환경변수 설정과 Firebase 연동하는 부분의 코드 입니다.

 

1
2
3
4
5
6
7
private void Form1_Load(object sender, EventArgs e)
{
    string path = AppDomain.CurrentDomain.BaseDirectory + @"cs-firebase-blog-firebase-adminsdk-18cwe-b5971a4787.json";
    Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", path);
 
    db = FirestoreDb.Create("cs-firebase-blog");
}
cs

3줄에 있는 .json 파일은 비공개 키의 이름을 적으시면 되고,

6줄에 있는 DB이름은 본인이 만들었던 Firebase DB이름을 적어주시면 됩니다.

 

본인의 DB이름은 Firebase에서 확인할 수 있습니다.

 

중간 체크 (중간 코드)

여기까지 한 내용을 실행시켰을 때, 오류가 나셨다면 중간에 잘못 설정한 구간이 있는 것 입니다.

다시한번 살펴보시고 따라와주시길 바랍니다.

그래도 정 모르시겠다면, 아래의 코드를 참고하시길 바랍니다.

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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Google.Cloud.Firestore;
 
namespace NetFirebase_Blog
{
    public partial class Form1 : Form
    {
        FirestoreDb db;
        public Form1()
        {
            InitializeComponent();
 
 
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + @"cs-firebase-blog-firebase-adminsdk-18cwe-b5971a4787.json";
            Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", path);
 
            db = FirestoreDb.Create("cs-firebase-blog");
        }
    }
}
cs

 

 

 

Part 3. 문서 생성

버튼 하나를 생성한 뒤에 클릭 이벤트 함수를 생성해줍니다.

 

Add_Document_with_AutoID메서드를 선언해 줍니다.

아래의 함수는 랜덤 ID로 문서를 설정해주는 코드 입니다.

Dictionary로 데이터를 집어넣는다는 것을 볼 수 있습니다.

 

대략 이렇게 사용을 하는구나 라고 알아두시면 되겠습니다.

1
2
3
4
5
6
7
8
9
10
11
12
void Add_Document_with_AutoID()
{
    CollectionReference coll = db.Collection("Add_Document_Width_AutoID");
    Dictionary<stringobject> data1 = new Dictionary<stringobject>()
    {
        {"FirestName""Kim" },
        {"LastName","Jinwon" },
        {"PhoneNumber""010-1234-5678" }
    };
    coll.AddAsync(data1);
    MessageBox.Show("data added successfully");
}
cs

 

그런 후 버튼 클릭 이벤트에 해당 함수가 실행될 수 있도록 해줍니다.

1
2
3
4
private void button1_Click(object sender, EventArgs e)
{
    Add_Document_with_AutoID();
}
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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Google.Cloud.Firestore;
 
namespace NetFirebase_Blog
{
    public partial class Form1 : Form
    {
        FirestoreDb db;
        public Form1()
        {
            InitializeComponent();
 
 
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + @"cs-firebase-blog-firebase-adminsdk-18cwe-b5971a4787.json";
            Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", path);
 
            db = FirestoreDb.Create("cs-firebase-blog");
        }
        private void button1_Click(object sender, EventArgs e)
        {
            Add_Document_with_AutoID();
        }
 
 
 
        void Add_Document_with_AutoID()
        {
            CollectionReference coll = db.Collection("Add_Document_Width_AutoID");
            Dictionary<stringobject> data1 = new Dictionary<stringobject>()
            {
                {"FirestName""Kim" },
                {"LastName","Jinwon" },
                {"PhoneNumber""010-1234-5678" }
            };
            coll.AddAsync(data1);
            MessageBox.Show("data added successfully");
        }
    }
}
 
cs

댓글