首页 > 解决方案 > 使用 Nuget 安装的 .net 项目上的 Firebase Admin SDK 总是给我一个错误

问题描述

我正在尝试使用 nuget 在 .Net 应用程序上安装 Firebase Admin。一切看起来都不错:

但是,每次我尝试使用包含 FirebaseAdmin 类的方法时,它都会引发 System.IO.FileNotFoundException。我尝试了许多解决方案:

没有什么。还有其他人有这个错误吗?如果是这样,您是如何解决的?

PS我在Nuget上有点绿色。我一直在从事一个使用它几年的项目。我的理解是它应该是一个流线型和简单的包管理器。直到现在我还没有安装一个新的包。我的经验不过如此——​​直到现在,了解一个所谓的优秀包管理器的来龙去脉一直在我的优先级列表的底部。欢迎任何帮助,甚至是相对明显的指示。

编辑 1:我知道 Firebase 需要初始化,但我一直试图将初始化放在模型的方法中,而不是项目启动中。

namespace Sis.OneSis.Business.Models.Notification
{
    [DataContract]
    public class NotificationFramework
    {

    #region Methods
    public static void SendNotification(int userId, int siteId, int yearId, string enumeration, int object_ID, string payload)
    {

        try
        {
            // Running the stored procedure
            V10Data.V10DataContextProvider modelContainer = new V10Data.V10DataContextProvider();
            List<SqlParameter> parameterList = new List<SqlParameter>();
            parameterList.Add(new SqlParameter { ParameterName = "@Enumeration", Value = enumeration, SqlDbType = SqlDbType.VarChar, Direction = ParameterDirection.Input });
            parameterList.Add(new SqlParameter { ParameterName = "@Payload", Value = payload, SqlDbType = SqlDbType.Xml, Direction = ParameterDirection.Input });
            parameterList.Add(new SqlParameter { ParameterName = "@Object_ID", Value = object_ID, SqlDbType = SqlDbType.Int, Direction = ParameterDirection.Input });
            parameterList.Add(new SqlParameter { ParameterName = "@User_ID", Value = userId, SqlDbType = SqlDbType.Int, Direction = ParameterDirection.Input });
            parameterList.Add(new SqlParameter { ParameterName = "@Site_ID", Value = siteId, SqlDbType = SqlDbType.Int, Direction = ParameterDirection.Input });
            parameterList.Add(new SqlParameter { ParameterName = "@Year_ID", Value = yearId, SqlDbType = SqlDbType.Int, Direction = ParameterDirection.Input });
            DataSet dataSet = modelContainer.ExecuteGetProcedure("spNTF_ProcessNotification", parameterList);

            // Retrieving the notifications
            List<NotificationLogDTO> notificationLogs = new List<NotificationLogDTO>();
            foreach (DataRow row in dataSet.Tables[0].Rows)
            {
                NotificationLogDTO notificationLog = new NotificationLogDTO();
                notificationLog.ID = row.Field<int>("ID");
                notificationLog.NotificationType_ID = row.Field<int>("NotificationType_ID");
                notificationLog.NotificationEvent_ID = row.Field<int>("NotificationEvent_ID");
                notificationLog.User_ID = row.Field<int>("User_ID");
                notificationLog.Object_ID = row.Field<int>("Object_ID");
                notificationLog.Student_ID = row.Field<int?>("Student_ID");
                notificationLog.Message = row.Field<string>("Message");
                notificationLog.Subject = row.Field<string>("Subject");
                notificationLog.AddedOn = row.Field<DateTime>("AddedOn");
                notificationLog.AddedBy = row.Field<int>("AddedBy"); 
                notificationLog.EmailAddress = row.Field<string>("EmailAddress");
                notificationLogs.Add(notificationLog);
            }

            // Sending the notifications
            using (CrudEngine crudEngine = new CrudEngine())
            {
                string defaultEmailAddress = "noreply@tylertech.com";
                var version = Sis.OneSis.Server.Configuration.AppConfiguration.RetrieveResourceVersion();
                if (version != null)
                {
                    if (version.Value == "V9")
                    {
                        defaultEmailAddress = crudEngine.Read<V9DomainModel.tblDistrict>()
                            .Where(o => o.blnExternal == false)
                            .Select(o => o.strEmailDefaultEAddress)
                            .SingleOrDefault();
                    } else
                    {
                        defaultEmailAddress = crudEngine.Read<V10DomainModel.SystemSetting>()
                            .Select(o => o.NotificationEmail)
                            .SingleOrDefault();
                    }
                }
                Dictionary<int, List<NotificationLogDTO>> userMobileNotifications = new Dictionary<int, List<NotificationLogDTO>>();
                foreach (NotificationLogDTO notification in notificationLogs)
                {
                    switch (notification.NotificationType_ID)
                    {
                        // Email
                        case 1:
                            SendEmailParameters parameters = new SendEmailParameters();
                            parameters.EmailFrom = defaultEmailAddress;
                            parameters.EmailTo = notification.EmailAddress;
                            parameters.Body = notification.Message;
                            parameters.Subject = notification.Subject;
                            sendEmailDTO.SendEmail(parameters, -1, -1, -1, userId, "Classroom");
                            break;

                        // Mobile Notification
                        case 3:
                            if (!userMobileNotifications.Keys.Contains(notification.User_ID))
                            {
                                userMobileNotifications.Add(notification.User_ID, new List<NotificationLogDTO>());
                            }
                            userMobileNotifications[notification.User_ID].Add(notification);
                            break;
                    }
                }

                // Sending mobile notifications
                FirebaseApp firebaseApp = FirebaseApp.DefaultInstance;
                if (firebaseApp == null)
                {
                    DataTable credentials = modelContainer.ExecuteSqlQuery("SELECT TOP 1 * FROM NTF_FirebaseCredentials");
                    if (credentials.Rows.Count > 0)
                    {
                        string firebaseJSON = credentials.Rows[0].Field<string>("FirebaseJSON");
                        FirebaseApp.Create(new AppOptions()
                        {
                            Credential = GoogleCredential.FromJson(firebaseJSON),
                        });
                    }
                }
                FirebaseMessaging firebaseMessaging = FirebaseMessaging.DefaultInstance;
                if (firebaseMessaging == null)
                {
                    firebaseMessaging = FirebaseMessaging.GetMessaging(firebaseApp);
                }
                List<NotificationUserDevice> userDevices = NotificationUserDevice.GetUserDevices(userId, userMobileNotifications.Keys.ToList());
                List<Message> messages = new List<Message>();
                foreach (NotificationUserDevice userDevice in userDevices)
                {
                    List<NotificationLogDTO> notifications = userMobileNotifications[userDevice.User_ID];
                    foreach (NotificationLogDTO notification in notifications)
                    {
                        Message message = new Message();
                        message.Token = userDevice.DeviceToken;
                        FirebaseAdmin.Messaging.Notification mobileNotification = new FirebaseAdmin.Messaging.Notification();
                        mobileNotification.Title = notification.Subject;
                        mobileNotification.Body = notification.Message;
                        message.Notification = mobileNotification;
                    }
                }
                firebaseMessaging.SendAllAsync(messages);
            }
        }
        catch (Exception ex)
        {
            string errMsg = "An error occurred -";
            LogServices.Error(ex, "userId:{0}:customMessage:{1}:", userId, errMsg);
            throw ex;
        }
    }
}

标签: c#.netfirebasenugetfirebase-admin

解决方案


Your understanding of NuGet is accurate for the vast majority of packages however FirebaseAdmin requires some additional set-up.

The whole process is described in detail here: https://firebase.google.com/docs/admin/setup#initialize-sdk

I will point out the most important things here (like a TL;DR). Firstly you will need a firebase private key in the form of a json file (steps described succinctly in the link under "Initialize the SDK"). After that, make sure you run this bit of code before any calls to firebase related functions.

FirebaseApp.Create(new AppOptions()
{
    Credential = GoogleCredential.FromFile("path/to/what/you/downlowded.json"),
});

I hope this solves your issue.


推荐阅读