/// <summary>
        /// Singleton 응용 프로그램 개체를 초기화합니다.  이것은 실행되는 작성 코드의 첫 번째
        /// 줄이며 따라서 main() 또는 WinMain()과 논리적으로 동일합니다.
        /// </summary>
        public App()
        {
            this.InitializeComponent();
            this.Suspending += OnSuspending;

            /*** Injecting objects to public static instances ***/

            // App
            MobileService = new MobileServiceClient(
                "https://pinthecloud.azure-mobile.net/",
                "yvulzHAGRgNsGnPLHKcEFCPJcuyzKj23"
            );
            ApplicationSessions = new WSApplicationSessions();
            ApplicationSettings = new WSApplicationSettings();

            // Manager
            SpotManager = new SpotManager();
            Geolocator = new Geolocator();
            BlobStorageManager = new BlobStorageManager();
            LocalStorageManager = new LocalStorageManager();

            OneDriveManager = new OneDriveManager();
            DropBoxManager = new DropboxManager();
            GoogleDriveManger = new GoogleDriveManager();

            /////////////////////////////////////////////////////
            // This order will be displayed at every App Pages
            /////////////////////////////////////////////////////
            StorageHelper.AddStorageManager(OneDriveManager.GetStorageName(), OneDriveManager);
            StorageHelper.AddStorageManager(DropBoxManager.GetStorageName(), DropBoxManager);
            StorageHelper.AddStorageManager(GoogleDriveManger.GetStorageName(), GoogleDriveManger);
            Switcher.SetStorageToMainPlatform();
            AccountManager = new AccountManager();
        }
Exemple #2
0
        public void ProcessData()
        {
            try
            {
                if (!((string.IsNullOrEmpty(ConfigurationSettings.PiServer)) || (string.IsNullOrEmpty(ConfigurationSettings.AzureConnectionString)) || (string.IsNullOrEmpty(ConfigurationSettings.StorageConnectionString)) ||
                      (string.IsNullOrEmpty(ConfigurationSettings.BlobContainerName))))
                {
                    Console.WriteLine("Init ProcessData");
                    ConnectionManager.Instance().Initialize();
                    Console.WriteLine("Done with Console manager initialization");
                    BlobStorageManager.Instance().ConfigureBlobStorage();
                    Console.WriteLine("Done with Blob Storage configuration");

                    string piServer = ConnectionManager.Instance().GetPIServer();
                    Thread piThread = new Thread(() => { ProcessDataByPIServer(piServer); });
                    piThread.Start();
                    Thread sensorThread = new Thread(() => { InsertSensorData(piServer); });
                    sensorThread.Start();
                }
                else
                {
                    Console.WriteLine("Doesn't have sufficient data in app config for connection");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error occured in processData" + e.Message);
            }
        }
Exemple #3
0
        public async Task <CopyFromUriOperation> CopyBlobFromUri(Uri source, string blobName, string containerName, CancellationToken cancellationToken = default)
        {
            BlobClient client =
                BlobStorageManager.GetBlobClient(
                    azureStorageOptions: _azureStorageOptions,
                    containerName: containerName,
                    blobName: blobName);

            try
            {
                IDictionary <string, string> metaData = new Dictionary <string, string>();
                metaData.Add(new KeyValuePair <string, string>("sourceFullUrl", source.AbsoluteUri));
                metaData.Add(new KeyValuePair <string, string>("sourceFullPath", source.AbsolutePath));

                return(await client.StartCopyFromUriAsync(source : source, metadata : metaData, cancellationToken : cancellationToken));
            }
            catch (Exception ex)
            {
                throw new BlobServiceException(
                          message: ex.Message,
                          blobName: blobName,
                          containerName: containerName,
                          methodName: nameof(CopyBlobFromUri),
                          innerException: ex);
            }
        }
Exemple #4
0
        public async Task <BlobContentInfo> UploadBlob(Stream objectStream, string blobName, string containerName, IDictionary <string, string> metaData, bool allowAnonymousRead = false, CancellationToken cancellationToken = default)
        {
            PublicAccessType publicAccessType = allowAnonymousRead ? PublicAccessType.Blob : PublicAccessType.None;
            BlobClient       client           =
                BlobStorageManager.GetBlobClient(
                    azureStorageOptions: _azureStorageOptions,
                    containerName: containerName,
                    blobName: blobName,
                    publicAccessType: publicAccessType);

            try
            {
                return(await client.UploadAsync(
                           content : objectStream,
                           metadata : metaData,
                           cancellationToken : cancellationToken));
            }
            catch (Exception ex)
            {
                throw new BlobServiceException(
                          message: ex.Message,
                          blobName: blobName,
                          containerName: containerName,
                          methodName: nameof(UploadBlob),
                          innerException: ex);
            }
        }
Exemple #5
0
        public async Task <bool> SetContainerMetaData(string containerName, IDictionary <string, string> metaData, CancellationToken cancellationToken = default)
        {
            BlobContainerClient containerClient = BlobStorageManager.GetBlobContainerClient(_azureStorageOptions, containerName);

            Response <BlobContainerInfo> result = await containerClient.SetMetadataAsync(metadata : metaData, cancellationToken : cancellationToken);

            return(result.GetRawResponse().Status == (int)HttpStatusCode.OK);
        }
Exemple #6
0
        private static void Main(string[] args)
        {
            var config = new BlobStorageConnectionDetails("mynewstorageaccnt",
                                                          "R3FFPLqamAfvzpHjx3mJDpC5EHRxzKtTpCiOKgyIjYAd+L59QWHlLRnYlZXcha7pHJ7O/01G5MrpvDcydmfaHw==",
                                                          "mycontainer", "my/root/folder/", "my/archive/folder/");
            var eventHubConfig = new EventHubConnectionDetails("myneweventhub-ns", "myneweventhub",
                                                               "RootManageSharedAccessKey", "52vBalJmNMvgITAvpffQ+6NGFTsyoMNUWlFekLJSxNw=");

            var deviceDetails = new DeviceSendingDetails()
            {
                FailureConditions = new[]
                {
                    new FailedDeviceSettings(3, 0.2F, SensorTypes.Energy),
                    new FailedDeviceSettings(8, 0.3F, SensorTypes.Energy),
                    new FailedDeviceSettings(16, 0.05F, SensorTypes.Energy),
                    new FailedDeviceSettings(19, 0.07F, SensorTypes.Energy),
                    new FailedDeviceSettings(22, 0.25F, SensorTypes.Energy),
                    new FailedDeviceSettings(2, 0.2F, SensorTypes.Light),
                    new FailedDeviceSettings(4, 0.2F, SensorTypes.Light),
                    new FailedDeviceSettings(7, 0.3F, SensorTypes.Light),
                    new FailedDeviceSettings(18, 0.05F, SensorTypes.Light),
                    new FailedDeviceSettings(5, 0.1F, SensorTypes.Humidity),
                    new FailedDeviceSettings(6, 0.2F, SensorTypes.Humidity),
                    new FailedDeviceSettings(8, 0.3F, SensorTypes.Humidity),
                    new FailedDeviceSettings(19, 0.05F, SensorTypes.Humidity),
                    new FailedDeviceSettings(20, 0.07F, SensorTypes.Humidity),
                    new FailedDeviceSettings(3, 0.1F, SensorTypes.Temperature),
                    new FailedDeviceSettings(6, 0.2F, SensorTypes.Temperature),
                    new FailedDeviceSettings(9, 0.3F, SensorTypes.Temperature),
                    new FailedDeviceSettings(12, 0.05F, SensorTypes.Temperature),
                    new FailedDeviceSettings(15, 0.07F, SensorTypes.Temperature),
                    new FailedDeviceSettings(18, 0.15F, SensorTypes.Temperature),
                    new FailedDeviceSettings(21, 0.25F, SensorTypes.Temperature),
                },
                NumberOfRooms       = 10,
                IterationSeconds    = 30,
                NumberOfDevices     = 50,
                NumberOfDeviceTypes = 4,
                TemperatureMax      = 28.9F,
                TemperatureMin      = 19.6F,
                HumidityMin         = 40.0F,
                HumidityMax         = 80.0F,
                EnergyMin           = 2000.0F,
                EnergyMax           = 4900.0F,
                LightMin            = 10.0F,
                LightMax            = 1800.0F,
                MillisecondDelay    = 1000,
                RedirectToLocalFile = true,
                RedirectFileName    = "c:\\\\tmp\\messages.txt"
            };
            var manager = new BlobStorageManager(config);
            var lines   = manager.GetLines("messages.txt");

            var sender = new MessageSender(eventHubConfig, deviceDetails);

            sender.SendMessages(lines);
        }
Exemple #7
0
        public async Task <BlobContainerPropertiesAndBlobList> GetContainerPropertiesAndFullDetails(string containerName, CancellationToken cancellationToken = default)
        {
            BlobContainerClient containerClient = BlobStorageManager.GetBlobContainerClient(_azureStorageOptions, containerName);

            BlobContainerProperties blobContainerProperties = await containerClient.GetPropertiesAsync();

            IEnumerable <BlobItem> blobContainerContent = containerClient.GetBlobs();

            return(new BlobContainerPropertiesAndBlobList
            {
                BlobContainerProperties = blobContainerProperties,
                BlobItems = blobContainerContent.ToArray(),
            });
        }
Exemple #8
0
        public async Task <bool> SetContainerAccessType(string containerName, PublicAccessType accessType, CancellationToken cancellationToken = default)
        {
            try
            {
                BlobContainerClient containerClient = BlobStorageManager.GetBlobContainerClient(_azureStorageOptions, containerName.ToLower(), accessType);

                _ = await containerClient.SetAccessPolicyAsync(accessType : accessType);

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Exemple #9
0
        private static async Task <PhotoResponseForBlobStorage> UploadPhotoToBlobStorageAsync
            (Stream photo, string photoName, string userId)
        {
            PhotoResponseForBlobStorage photoResponse = new PhotoResponseForBlobStorage();

            using (BlobStorageManager blobStorageManager = new BlobStorageManager(Variables.BlobStorageConnectionString, userId))
            {
                var response = await blobStorageManager.AddDocumentAsync(photo, photoName);

                if (response.IsSuccess)
                {
                    photoResponse.PhotoPhat = blobStorageManager.GetDocumentPath(photoName);
                }
            }

            return(photoResponse);
        }
Exemple #10
0
        public async Task <bool> AppendContainerMetaData(string containerName, IDictionary <string, string> metaData, CancellationToken cancellationToken = default)
        {
            BlobContainerClient containerClient = BlobStorageManager.GetBlobContainerClient(_azureStorageOptions, containerName);

            BlobContainerProperties blobContainerProperties = await containerClient.GetPropertiesAsync();

            IDictionary <string, string> existingMetaData = blobContainerProperties.Metadata;

            foreach (KeyValuePair <string, string> metaItem in metaData)
            {
                existingMetaData.Add(metaItem);
            }

            Response <BlobContainerInfo> result = await containerClient.SetMetadataAsync(metadata : metaData, cancellationToken : cancellationToken);

            return(result.GetRawResponse().Status == (int)HttpStatusCode.OK);
        }
Exemple #11
0
        public async Task <bool> BlobExists(string blobName, string containerName, CancellationToken cancellationToken)
        {
            BlobContainerClient containerClient = BlobStorageManager.GetBlobContainerClient(
                azureStorageOptions: _azureStorageOptions,
                blobContainerName: containerName);

            try
            {
                BlobClient blob = containerClient.GetBlobClient(blobName);
                return(await blob.ExistsAsync(cancellationToken : cancellationToken));
            }
            catch (Exception ex)
            {
                throw new BlobServiceException(
                          message: ex.Message,
                          blobName: blobName,
                          containerName: containerName,
                          methodName: nameof(BlobExists),
                          innerException: ex);
            }
        }
Exemple #12
0
        public async Task <bool> UpdateBlobMetaData(string blobName, string containerName, IDictionary <string, string> metaData, CancellationToken cancellationToken = default)
        {
            BlobClient client =
                BlobStorageManager.GetBlobClient(
                    azureStorageOptions: _azureStorageOptions,
                    containerName: containerName,
                    blobName: blobName);

            try
            {
                BlobProperties properties = await client.GetPropertiesAsync(cancellationToken : cancellationToken);

                IDictionary <string, string> existingMetaData = properties.Metadata;

                foreach (KeyValuePair <string, string> item in metaData)
                {
                    if (existingMetaData.ContainsKey(item.Key))
                    {
                        existingMetaData[item.Key] = item.Value;
                    }
                    else
                    {
                        existingMetaData.Add(item);
                    }
                }

                Azure.Response <BlobInfo> response = await client.SetMetadataAsync(metadata : existingMetaData, cancellationToken : cancellationToken);

                return(response.GetRawResponse().Status == (int)HttpStatusCode.OK);
            }
            catch (Exception ex)
            {
                throw new BlobServiceException(
                          message: ex.Message,
                          blobName: blobName,
                          containerName: containerName,
                          methodName: nameof(UpdateBlobMetaData),
                          innerException: ex);
            }
        }
Exemple #13
0
        public async Task <bool> DeleteBlobIfExists(string blobName, string containerName, CancellationToken cancellationToken = default)
        {
            BlobClient client =
                BlobStorageManager.GetBlobClient(
                    azureStorageOptions: _azureStorageOptions,
                    containerName: containerName,
                    blobName: blobName);

            try
            {
                return(await client.DeleteIfExistsAsync(cancellationToken : cancellationToken));
            }
            catch (Exception ex)
            {
                throw new BlobServiceException(
                          message: ex.Message,
                          blobName: blobName,
                          containerName: containerName,
                          methodName: nameof(DeleteBlobIfExists),
                          innerException: ex);
            }
        }
Exemple #14
0
        public async Task <BlobSnapshotInfo> CreateBlobSnapshot(string blobName, string containerName, CancellationToken cancellationToken = default)
        {
            BlobClient client =
                BlobStorageManager.GetBlobClient(
                    azureStorageOptions: _azureStorageOptions,
                    containerName: containerName,
                    blobName: blobName);

            try
            {
                return(await client.CreateSnapshotAsync(cancellationToken : cancellationToken));
            }
            catch (Exception ex)
            {
                throw new BlobServiceException(
                          message: ex.Message,
                          blobName: blobName,
                          containerName: containerName,
                          methodName: nameof(CreateBlobSnapshot),
                          innerException: ex);
            }
        }
        /// <summary>
        /// Singleton 응용 프로그램 개체를 초기화합니다.  이것은 실행되는 작성 코드의 첫 번째
        /// 줄이며 따라서 main() 또는 WinMain()과 논리적으로 동일합니다.
        /// </summary>
        public App()
        {
            this.InitializeComponent();
            this.Suspending += OnSuspending;



            /*** Injecting objects to public static instances ***/

            // App
            MobileService = new MobileServiceClient(
                "https://pinthecloud.azure-mobile.net/",
                "yvulzHAGRgNsGnPLHKcEFCPJcuyzKj23"
                );
            ApplicationSessions = new WSApplicationSessions();
            ApplicationSettings = new WSApplicationSettings();

            // Manager
            SpotManager         = new SpotManager();
            Geolocator          = new Geolocator();
            BlobStorageManager  = new BlobStorageManager();
            LocalStorageManager = new LocalStorageManager();

            OneDriveManager   = new OneDriveManager();
            DropBoxManager    = new DropboxManager();
            GoogleDriveManger = new GoogleDriveManager();


            /////////////////////////////////////////////////////
            // This order will be displayed at every App Pages
            /////////////////////////////////////////////////////
            StorageHelper.AddStorageManager(OneDriveManager.GetStorageName(), OneDriveManager);
            StorageHelper.AddStorageManager(DropBoxManager.GetStorageName(), DropBoxManager);
            StorageHelper.AddStorageManager(GoogleDriveManger.GetStorageName(), GoogleDriveManger);
            Switcher.SetStorageToMainPlatform();
            AccountManager = new AccountManager();
        }
Exemple #16
0
        public async Task <bool> AbortCopyBlobFromUri(string copyOperationId, string blobName, string containerName, CancellationToken cancellationToken)
        {
            BlobClient client =
                BlobStorageManager.GetBlobClient(
                    azureStorageOptions: _azureStorageOptions,
                    containerName: containerName,
                    blobName: blobName);

            try
            {
                Azure.Response response = await client.AbortCopyFromUriAsync(copyId : copyOperationId, cancellationToken : cancellationToken);

                return(response.Status == (int)HttpStatusCode.OK);
            }
            catch (Exception ex)
            {
                throw new BlobServiceException(
                          message: ex.Message,
                          blobName: blobName,
                          containerName: containerName,
                          methodName: nameof(AbortCopyBlobFromUri),
                          innerException: ex);
            }
        }
Exemple #17
0
        public async Task <bool> DownloadBlobTo(Stream destination, string blobName, string containerName, CancellationToken cancellationToken = default)
        {
            BlobClient client =
                BlobStorageManager.GetBlobClient(
                    azureStorageOptions: _azureStorageOptions,
                    containerName: containerName,
                    blobName: blobName);

            try
            {
                Azure.Response response = await client.DownloadToAsync(destination);

                return(response.Status == (int)HttpStatusCode.Created);
            }
            catch (Exception ex)
            {
                throw new BlobServiceException(
                          message: ex.Message,
                          blobName: blobName,
                          containerName: containerName,
                          methodName: nameof(DownloadBlobTo),
                          innerException: ex);
            }
        }
Exemple #18
0
        public async Task <bool> UndeleteBlob(string blobName, string containerName, CancellationToken cancellationToken = default)
        {
            BlobClient client =
                BlobStorageManager.GetBlobClient(
                    azureStorageOptions: _azureStorageOptions,
                    containerName: containerName,
                    blobName: blobName);

            try
            {
                Azure.Response response = await client.UndeleteAsync(cancellationToken : cancellationToken);

                return(response.Status == (int)HttpStatusCode.OK);
            }
            catch (Exception ex)
            {
                throw new BlobServiceException(
                          message: ex.Message,
                          blobName: blobName,
                          containerName: containerName,
                          methodName: nameof(UndeleteBlob),
                          innerException: ex);
            }
        }
Exemple #19
0
        public async Task <bool> SetBlobMetaData(string blobName, string containerName, IDictionary <string, string> metaData, CancellationToken cancellationToken = default)
        {
            BlobClient client =
                BlobStorageManager.GetBlobClient(
                    azureStorageOptions: _azureStorageOptions,
                    containerName: containerName,
                    blobName: blobName);

            try
            {
                Azure.Response <BlobInfo> response = await client.SetMetadataAsync(metadata : metaData, cancellationToken : cancellationToken);

                return(response.GetRawResponse().Status == (int)HttpStatusCode.OK);
            }
            catch (Exception ex)
            {
                throw new BlobServiceException(
                          message: ex.Message,
                          blobName: blobName,
                          containerName: containerName,
                          methodName: nameof(SetBlobMetaData),
                          innerException: ex);
            }
        }
Exemple #20
0
        public void InsertSensorData(string piServerName, double timeZone)
        {
            try
            {
                var sensorList = this.GetSensors(piServerName);

                ProcessedSensorDataModel processedDataInfo = BlobStorageManager.Instance().GetLastProcessedData <ProcessedSensorDataModel>(piServerName, Constants.THRESHOLD_SENSOR_STORAGE_FILENAME_PREFIX);
                if (processedDataInfo == null)
                {
                    processedDataInfo = new ProcessedSensorDataModel();
                }

                DateTime processedTimestamp  = processedDataInfo.ProcessedTimestamp;
                DateTime firstEntryTimeStamp = processedTimestamp;
                //To do need to check this
                if (processedTimestamp == null || processedTimestamp == DateTime.MinValue || processedTimestamp == default(DateTime))
                {
                    SqlConnection sensorFirstEntryConn = ConnectionManager.Instance().GetPISQLConnection(piServerName);
                    ConnectionManager.Instance().OpenSQLConnection(sensorFirstEntryConn);
                    //Read data from PI Server
                    SqlCommand getTimestamp = new SqlCommand("SELECT TOP 1 TimeStamp FROM SensorData order by Timestamp", sensorFirstEntryConn);

                    SqlDataReader result = getTimestamp.ExecuteReader();
                    while (result.Read()) //Runs only once
                    {
                        firstEntryTimeStamp = (DateTime)result[0];
                    }
                    ConnectionManager.Instance().CloseSQLConnection(sensorFirstEntryConn);
                }

                SqlConnection getPiSensorDataConn = ConnectionManager.Instance().GetPISQLConnection(piServerName);
                ConnectionManager.Instance().OpenSQLConnection(getPiSensorDataConn);
                SqlCommand getPiSensorDataCommand = (processedTimestamp == null || processedTimestamp == DateTime.MinValue || processedTimestamp == default(DateTime)) ? new SqlCommand("SELECT * FROM SensorData WHERE TimeStamp >= @TimeStamp", getPiSensorDataConn) : new SqlCommand("SELECT * FROM SensorData WHERE TimeStamp > @TimeStamp", getPiSensorDataConn);
                processedTimestamp = firstEntryTimeStamp;

                getPiSensorDataCommand.Parameters.Add(new SqlParameter("@TimeStamp", processedTimestamp));
                SqlDataReader piSensorDataReader = getPiSensorDataCommand.ExecuteReader();
                try
                {
                    while (piSensorDataReader.Read())
                    {
                        var sensorDetail = sensorList.Where(sensor => sensor.Sensor_Name.Equals(piSensorDataReader["Name"])).FirstOrDefault();
                        if (sensorDetail == null)
                        {
                            this.AddNewSensorToAzureAndGenerateNotification(piSensorDataReader["Name"].ToString(), piServerName);
                            //reinit sensor list after insertion of new sensor
                            sensorList   = this.GetSensors(piServerName);
                            sensorDetail = sensorList.Where(sensor => sensor.Sensor_Name.Equals(piSensorDataReader["Name"])).FirstOrDefault();
                            this.AddNewAlert(0, sensorDetail.Sensor_Id, "Device Alert", "New device found with name " + sensorDetail.Sensor_Name, DateTime.UtcNow, 0, piServerName);
                        }
                        DateTime utcDate;
                        DateTime localDate;
                        DateTime.TryParse(piSensorDataReader["TimeStamp"].ToString(), out utcDate);
                        localDate = utcDate.AddHours(Convert.ToDouble(timeZone));
                        var formattedDate = localDate.ToString(Constants.DATE_TIME_FORMAT);

                        SqlConnection azureSQLConnection = new SqlConnection();
                        azureSQLConnection.ConnectionString = ConfigurationSettings.AzureConnectionString;
                        azureSQLConnection.Open();
                        SqlCommand updateAzureDBCommand = new SqlCommand("INSERT INTO SensorLiveData (Sensor_Id,Temperature,Brightness,Humidity,Timestamp,PiServerName) VALUES (@SensorId,@Temperature,@Brightness,@Humidity,@Timestamp,@PiServerName)", azureSQLConnection);
                        updateAzureDBCommand.Parameters.Add(new SqlParameter("@SensorId", sensorDetail.Sensor_Id));
                        updateAzureDBCommand.Parameters.Add(new SqlParameter("@Temperature", piSensorDataReader["Temperature"]));
                        updateAzureDBCommand.Parameters.Add(new SqlParameter("@Brightness", piSensorDataReader["Brightness"]));
                        updateAzureDBCommand.Parameters.Add(new SqlParameter("@Humidity", piSensorDataReader["Humidity"]));
                        updateAzureDBCommand.Parameters.Add(new SqlParameter("@Timestamp", formattedDate));
                        updateAzureDBCommand.Parameters.Add(new SqlParameter("@PiServerName", piServerName));
                        updateAzureDBCommand.ExecuteNonQuery();
                        processedTimestamp = Convert.ToDateTime(piSensorDataReader["TimeStamp"]);
                        azureSQLConnection.Close();
                    }
                }
                catch (Exception e)
                {
                }
                finally
                {
                    ConnectionManager.Instance().CloseSQLConnection(getPiSensorDataConn);
                }
                processedDataInfo.ProcessedTimestamp = processedTimestamp;
                Console.WriteLine("Storing Sensor Details : " + processedDataInfo);
                BlobStorageManager.Instance().SetLastProcessedData <ProcessedSensorDataModel>(piServerName, Constants.THRESHOLD_SENSOR_STORAGE_FILENAME_PREFIX, processedDataInfo);
            }
            catch (Exception ex)
            {
            }
        }
        public override IEnumerable <Telerik.Sitefinity.Services.Search.Data.IDocument> GetConvertedItemsForMapping(Telerik.Sitefinity.Publishing.WrapperObject wrapperObject)
        {
            wrapperObject.SetOrAddProperty("CategoryIds", string.Empty);

            var contentItem = (((WrapperObject)wrapperObject.WrappedObject).WrappedObject) as IDynamicFieldsContainer ?? ((WrapperObject)((WrapperObject)((WrapperObject)wrapperObject.WrappedObject).WrappedObject).WrappedObject).WrappedObject as IDynamicFieldsContainer;

            if (contentItem != null)
            {
                var categories = contentItem.GetValue <IList <Guid> >("Category");
                if (categories != null)
                {
                    //remove the "-" from the guid since it's difficult to search for a special character
                    wrapperObject.SetOrAddProperty("CategoryIds", string.Join(" ", categories.Select(g => g.ToString().Replace("-", ""))));
                }
            }

            //different blogs get different treatment
            wrapperObject.SetOrAddProperty("ThumbnailUrl", string.Empty);
            if (wrapperObject.GetProperty("ContentType").ToString().Contains("BlogPost"))
            {
                //something used to be here
            }

            //map a few columns for types
            var objectType = ContentListHelper.SearchTypes();

            wrapperObject.SetOrAddProperty("ContentTypeName", string.Empty);
            wrapperObject.SetOrAddProperty("ContentTypeOrdinal", string.Empty);
            if (objectType != null)
            {
                var objectTypeName = objectType.FirstOrDefault(i => i.Item2 == (string)wrapperObject.GetProperty("ContentType"));
                wrapperObject.SetOrAddProperty("ContentTypeName", objectTypeName.Item1);
                wrapperObject.SetOrAddProperty("ContentTypeOrdinal", objectTypeName.Item3.ToString("000"));
            }

            //set the "PublishDate" as a string - lucene will only order by strings
            var publicationDate = (DateTime)wrapperObject.GetProperty("PublicationDate");

            wrapperObject.SetOrAddProperty("PublishDate", publicationDate.ToString("yyyy-MM-dd-HH-mm"));

            //set the "SortTitle" as a uppercase string - sorting by title didn't work very well...
            var sortTitle = wrapperObject.GetProperty("Title").ToString().Trim().ToLower().GenerateSlug().Replace("-", "");

            wrapperObject.SetOrAddProperty("SortTitle", sortTitle);


            wrapperObject.SetOrAddProperty("EventStart", string.Empty);
            wrapperObject.SetOrAddProperty("EventEnd", string.Empty);
            if (contentItem.DoesFieldExist("EventStart"))
            {
                var eventStart = contentItem.GetValue <DateTime?>("EventStart");
                var eventEnd   = contentItem.GetValue <DateTime?>("EventEnd");

                if (eventStart.HasValue)
                {
                    wrapperObject.SetProperty("EventStart", eventStart.Value.ToLocalTime().ToString());
                }

                if (eventEnd.HasValue)
                {
                    wrapperObject.SetProperty("EventEnd", eventEnd.Value.ToLocalTime().ToString());
                }
            }

            //index the content of attached files
            wrapperObject.SetOrAddProperty("DocumentText", string.Empty);
            wrapperObject.SetOrAddProperty("DocumentLink", string.Empty);
            if (wrapperObject.HasProperty("Document"))
            {
                var contentLink = wrapperObject.GetProperty("Document") as ContentLink[];
                if (contentLink != null)
                {
                    var librariesManager = LibrariesManager.GetManager();
                    var service          = ServiceBus.ResolveService <IDocumentService>();
                    foreach (var link in contentLink)
                    {
                        try
                        {
                            var document = librariesManager.GetDocument(link.ChildItemId);
                            var stream   = BlobStorageManager.GetManager(document.GetStorageProviderName()).GetDownloadStream(document);
                            var pdfText  = service.ExtractText(document.MimeType, stream);
                            wrapperObject.SetOrAddProperty("DocumentText", pdfText.Trim());
                            wrapperObject.SetOrAddProperty("DocumentLink", document.MediaUrl);
                        }
                        catch (Exception ex)
                        {
                            //log the error, but don't stop the index
                            LogManager.GetCurrentClassLogger().Warn(ex);
                        }
                    }
                }
            }

            if (wrapperObject.HasProperty("Page"))
            {
                //value looks like this in DB: "0619909c-4174-6fcd-88ea-ff000002c0f4;Policy & Initiatives > Policy Topics > Accessibility & Disability"
                var pageValue = wrapperObject.GetProperty("Page");

                if (pageValue != null && pageValue != "")
                {
                    var pageId        = Guid.Parse(pageValue.ToString().Split(';').First());
                    var pageManager   = PageManager.GetManager();
                    var pageNode      = pageManager.GetPageNode(pageId);
                    var pageData      = pageManager.GetPageDataList().First(d => d.Id == pageNode.PageId);
                    var contentBlocks = pageData.Controls.Where(c => c.ObjectType == typeof(ContentBlock).FullName);
                    var content       = string.Join(" ", contentBlocks.Select(c => ((ContentBlock)pageManager.LoadControl(c)).Html.StripHtmlTags()));

                    wrapperObject.SetOrAddProperty("Content", content);
                    wrapperObject.SetOrAddProperty("Link", pageNode.GetFullUrl());
                    wrapperObject.SetOrAddProperty("Title", pageNode.Title);
                }
            }

            return(base.GetConvertedItemsForMapping(wrapperObject));
        }
Exemple #22
0
 public async Task <bool> DeleteContainerAsync(string containerName, CancellationToken cancellationToken)
 => await BlobStorageManager.GetBlobContainerClient(
     azureStorageOptions : _azureStorageOptions,
     blobContainerName : containerName).DeleteIfExistsAsync(cancellationToken: cancellationToken);
Exemple #23
0
        void ProcessDataByPIServer(string piServerName)
        {
            while (true)
            {
                try
                {
                    double utcConversionTime = GetAndTimezone();

                    //To Do get connection basis of PI server using Connection Manager
                    SqlConnection piConnection = ConnectionManager.Instance().GetPISQLConnection(piServerName);
                    ConnectionManager.Instance().OpenSQLConnection(piConnection);
                    Console.WriteLine("Pi SQL Connection Opened");


                    SqlConnection weatherConnection = ConnectionManager.Instance().GetPISQLConnection(piServerName);
                    ConnectionManager.Instance().OpenSQLConnection(weatherConnection);


                    //We need this meterlist, bcoz we going to process data meter by meter
                    List <string> meterList = new List <string>();
                    meterList = getMeterList(piServerName);
                    ProcessedDataModel processedDataInfo = BlobStorageManager.Instance().GetLastProcessedData <ProcessedDataModel>(piServerName, Constants.THRESHOLD_METER_STORAGE_FILENAME_PREFIX);
                    if (processedDataInfo == null)
                    {
                        processedDataInfo = new ProcessedDataModel {
                            MeterTimestamp = new Dictionary <string, DateTime>()
                        }
                    }
                    ;
                    Dictionary <string, DateTime> meterTimestamp = processedDataInfo.MeterTimestamp;
                    //Todo need to add validation here at timestamp whether it is null or not, if it is null then have to add default value
                    meterList.All(meter =>
                    {
                        if (!meterTimestamp.ContainsKey(meter))
                        {
                            SqlConnection meterFirstEntryConn = ConnectionManager.Instance().GetPISQLConnection(piServerName);
                            ConnectionManager.Instance().OpenSQLConnection(meterFirstEntryConn);
                            SqlCommand getTimestamp = new SqlCommand("SELECT TOP 1 Timestamp FROM PowergridView WHERE PowerScout = @meter order by Timestamp", meterFirstEntryConn);
                            getTimestamp.Parameters.Add(new SqlParameter("meter", meter));
                            SqlDataReader result = getTimestamp.ExecuteReader();
                            while (result.Read()) //Runs only once
                            {
                                DateTime updatedTime = Utility.TrimDateToMinute(((DateTime)result[0]).AddMinutes(-1));
                                meterTimestamp.Add(meter, Convert.ToDateTime(updatedTime));
                            }
                            ConnectionManager.Instance().CloseSQLConnection(meterFirstEntryConn);
                        }

                        //This is bcoz we are saving value in threshold file with addition of utcconversion time in pidb time.So this condition should be basedon pi time
                        DateTime startTime = Utility.TrimDateToMinute(meterTimestamp[meter]);
                        DateTime endTime   = startTime.AddMinutes(Constants.TIME_WINDOW_FOR_HALF_HOURLY_DATA);

                        SqlCommand command;
                        //I know this code is wrong have to covert into timestamp string or add a certain value to timestamp to make proper timestamp
                        command = new SqlCommand("SELECT * FROM PowergridView WHERE PowerScout = @meter AND Timestamp > @startTime AND Timestamp <= @endTime ORDER BY Timestamp", piConnection);

                        // Add the parameters.
                        command.Parameters.Add(new SqlParameter("@startTime", startTime.ToString(Constants.DATE_TIME_FORMAT)));
                        command.Parameters.Add(new SqlParameter("@endTime", endTime.ToString(Constants.DATE_TIME_FORMAT)));
                        command.Parameters.Add(new SqlParameter("@meter", meter));

                        SqlDataReader pireader = command.ExecuteReader();
                        List <AzureDataModel> meterDataList = new List <AzureDataModel>();
                        DateTime lastProcessedDate          = DateTime.Now;
                        while (pireader.Read())
                        {
                            AzureDataModel data = new AzureDataModel();
                            string serialNumber = Convert.ToString(pireader["Serial Number"]);
                            DateTime utcDate;
                            DateTime.TryParse(pireader["Timestamp"].ToString(), out utcDate);

                            WeatherDetails weatherDetails = GetWeatherDetails(utcDate, weatherConnection);
                            lastProcessedDate             = utcDate;
                            utcDate = utcDate.AddHours(utcConversionTime);
                            var utcSQLFormattedDate = utcDate.ToString(Constants.DATE_TIME_FORMAT);

                            ClassScheduleManager.Instance().ReInitialize(piServerName);
                            ClassOccupanyDetails classDetails = ClassScheduleManager.Instance().ProcessDataRow(serialNumber, utcDate);

                            if (pireader["Id"] != DBNull.Value)
                            {
                                data.Id = Convert.ToInt32(pireader["Id"]);
                            }
                            if (pireader["Amps L1"] != DBNull.Value)
                            {
                                data.AMPS_L1 = Convert.ToDouble(pireader["Amps L1"]);
                            }
                            if (pireader["Amps L2"] != DBNull.Value)
                            {
                                data.AMPS_L2 = Convert.ToDouble(pireader["Amps L2"]);
                            }
                            if (pireader["Amps L3"] != DBNull.Value)
                            {
                                data.AMPS_L3 = Convert.ToDouble(pireader["Amps L3"]);
                            }
                            if (pireader["Amps System Avg"] != DBNull.Value)
                            {
                                data.AMPS_SYSTEM_AVG = Convert.ToDouble(pireader["Amps System Avg"]);
                            }
                            if (pireader["Breaker Details"] != DBNull.Value)
                            {
                                data.Breaker_details = Convert.ToString(pireader["Breaker Details"]);
                            }
                            if (pireader["Breaker Label"] != DBNull.Value)
                            {
                                data.Breaker_label = Convert.ToString(pireader["Breaker Label"]);
                            }
                            if (pireader["Building"] != DBNull.Value)
                            {
                                data.Building = Convert.ToString(pireader["Building"]);
                            }


                            data.ClassOccupanyRemaining = classDetails.ClassOccupanyRemaining;

                            data.ClassOccupiedValue = classDetails.ClassOccupiedValue;

                            data.TotalClassCapacity = classDetails.ClassTotalCapacity;

                            data.isClassOccupied = classDetails.IsClassOccupied;

                            if (pireader["Daily Electric Cost"] != DBNull.Value)
                            {
                                data.Daily_electric_cost = Convert.ToDouble(pireader["Daily Electric Cost"]);
                            }
                            if (pireader["Daily kWh System"] != DBNull.Value)
                            {
                                data.Daily_KWH_System = Convert.ToDouble(pireader["Daily kWh System"]);
                            }
                            if (pireader["kW L1"] != DBNull.Value)
                            {
                                data.KW_L1 = Convert.ToDouble(pireader["kW L1"]);
                            }
                            if (pireader["kW L2"] != DBNull.Value)
                            {
                                data.KW_L2 = Convert.ToDouble(pireader["kW L2"]);
                            }
                            if (pireader["kW L3"] != DBNull.Value)
                            {
                                data.KW_L3 = Convert.ToDouble(pireader["kW L3"]);
                            }
                            if (pireader["Monthly Electric Cost"] != DBNull.Value)
                            {
                                data.Monthly_electric_cost = Convert.ToDouble(pireader["Monthly Electric Cost"]);
                            }
                            if (pireader["Monthly kWh System"] != DBNull.Value)
                            {
                                data.Monthly_KWH_System = Convert.ToDouble(pireader["Monthly kWh System"]);
                            }
                            if (pireader["PowerScout"] != DBNull.Value)
                            {
                                data.PowerScout = Convert.ToString(pireader["PowerScout"]);
                            }
                            if (pireader["Rated Amperage"] != DBNull.Value)
                            {
                                data.Rated_Amperage = Convert.ToDouble(pireader["Rated Amperage"]);
                            }

                            data.Pressure = Convert.ToDouble(weatherDetails.Pressure);

                            data.Relative_humidity = Convert.ToDouble(weatherDetails.RelativeHumidity);

                            if (pireader["Rolling Hourly kWh System"] != DBNull.Value)
                            {
                                data.Rolling_hourly_kwh_system = Convert.ToDouble(pireader["Rolling Hourly kWh System"]);
                            }

                            if (pireader["Serial Number"] != DBNull.Value)
                            {
                                data.Serial_number = Convert.ToString(pireader["Serial Number"]);
                            }

                            data.Temperature = Convert.ToDouble(weatherDetails.Temperature);
                            //Check here
                            data.Timestamp = Convert.ToDateTime(utcSQLFormattedDate);

                            if (pireader["Type"] != DBNull.Value)
                            {
                                data.Type = Convert.ToString(pireader["Type"]);
                            }

                            data.Visibility = Convert.ToDouble(weatherDetails.Visibility);
                            if (pireader["Volts L1 to Neutral"] != DBNull.Value)
                            {
                                data.Volts_L1_to_neutral = Convert.ToDouble(pireader["Volts L1 to Neutral"]);
                            }
                            if (pireader["Volts L2 to Neutral"] != DBNull.Value)
                            {
                                data.Volts_L2_to_neutral = Convert.ToDouble(pireader["Volts L2 to Neutral"]);
                            }
                            if (pireader["Volts L3 to Neutral"] != DBNull.Value)
                            {
                                data.Volts_L3_to_neutral = Convert.ToDouble(pireader["Volts L3 to Neutral"]);
                            }
                            if (pireader["kW System"] != DBNull.Value)
                            {
                                data.kW_System = Convert.ToDouble(pireader["kW System"]);
                            }

                            data.PiServerName = piServerName;
                            meterDataList.Add(data);
                            meterTimestamp[meter] = lastProcessedDate;
                            //count++;
                        }
                        pireader.Close();
                        //Hack Hack Hack
                        if (meterDataList != null && meterDataList.Count != 0)
                        {
                            //This condition means we get all (29)entries of that perticular half hour
                            if (Utility.TrimDateToMinute(lastProcessedDate) == endTime.AddMinutes(-1))
                            {
                                Console.WriteLine("Now going to update Database");
                                updateDatabase(meterDataList);
                                processedDataInfo.MeterTimestamp = meterTimestamp;
                                Console.Write("Storing value to Blob : " + processedDataInfo);
                                BlobStorageManager.Instance().SetLastProcessedData <ProcessedDataModel>(piServerName, Constants.THRESHOLD_METER_STORAGE_FILENAME_PREFIX, processedDataInfo);
                            }
                            else
                            {
                                //will wait for half an hour if there is not all entries in selected half hour block i.e 29 entries
                                Console.WriteLine("**************Sleeping*******************");
                                Thread.Sleep(1800000);
                            }
                        }

                        return(true);
                    });


                    ConnectionManager.Instance().CloseSQLConnection(piConnection);
                    ConnectionManager.Instance().CloseSQLConnection(weatherConnection);
                }
                catch (Exception e)
                {
                    Console.WriteLine("*********Exception Occured ******" + e.Message);
                }
            }
        }
Exemple #24
0
 public async Task <BlobContainerProperties> GetContainerProperties(string containerName, CancellationToken cancellationToken)
 => await BlobStorageManager.GetBlobContainerClient(_azureStorageOptions, containerName).GetPropertiesAsync();
Exemple #25
0
        public async Task <BlobItem[]> ListContainerContentAsync(string containerName, CancellationToken cancellationToken = default)
        {
            IEnumerable <BlobItem> blobs = BlobStorageManager.GetBlobContainerClient(_azureStorageOptions, containerName).GetBlobs();

            return(await Task.FromResult(blobs.ToArray()));
        }
Exemple #26
0
        /// <summary>
        /// Application 개체의 생성자입니다.
        /// </summary>
        public App()
        {
            // Catch되지 않은 예외의 전역 처리기입니다.
            UnhandledException += Application_UnhandledException;

            // 표준 XAML 초기화
            InitializeComponent();

            // 전화 관련 초기화
            InitializePhoneApplication();

            // 언어 표시 초기화
            InitializeLanguage();



            /*** Injecting objects to public static instances ***/
            
            // App
            MobileService = new MobileServiceClient(
                "https://pinthecloud.azure-mobile.net/",
                "yvulzHAGRgNsGnPLHKcEFCPJcuyzKj23"
            );
            ApplicationSettings = IsolatedStorageSettings.ApplicationSettings;

            // Manager
            SpotManager = new SpotManager();
            Geolocator = new Geolocator();
            BlobStorageManager = new BlobStorageManager();
            LocalStorageManager = new LocalStorageManager();

            OneDriveManager = new OneDriveManager();
            DropBoxManager = new DropboxManager();
            GoogleDriveManger = new GoogleDriveManager();


            /////////////////////////////////////////////////////
            // This order will be displayed at every App Pages
            /////////////////////////////////////////////////////
            StorageHelper.AddStorageManager(OneDriveManager.GetStorageName(), OneDriveManager);
            StorageHelper.AddStorageManager(DropBoxManager.GetStorageName(), DropBoxManager);
            StorageHelper.AddStorageManager(GoogleDriveManger.GetStorageName(), GoogleDriveManger);
            Switcher.SetStorageToMainPlatform();
            AccountManager = new AccountManager();

            // 디버깅하는 동안 그래픽 프로파일링 정보를 표시합니다.
            if (Debugger.IsAttached)
            {
                // 현재 프레임 속도 카운터를 표시합니다.
                Application.Current.Host.Settings.EnableFrameRateCounter = true;

                // 각 프레임에서 다시 그려지는 응용 프로그램의 영역을 표시합니다.
                //Application.Current.Host.Settings.EnableRedrawRegions = true;

                // 색이 지정된 오버레이로 가속된 GPU에 전달되는 페이지 영역을 표시하는
                // 비프로덕션 분석 시각화 모드를 설정합니다.
                //Application.Current.Host.Settings.EnableCacheVisualization = true;

                // 응용 프로그램의 유휴 검색을 사용하지 않도록 설정하여 디버거를
                // 사용하는 동안 화면이 꺼지지 않도록 방지합니다.
                // 주의:- 디버그 모드에서만 사용합니다. 사용자 유휴 검색을 해제하는 응용 프로그램은 사용자가 전화를 사용하지 않을 경우에도
                // 계속 실행되어 배터리 전원을 소모합니다.
                PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
            }

        }
        public override IEnumerable <Telerik.Sitefinity.Services.Search.Data.IDocument> GetConvertedItemsForMapping(Telerik.Sitefinity.Publishing.WrapperObject wrapperObject)
        {
            var taxonomyManager = TaxonomyManager.GetManager();

            #region contentItem

            wrapperObject.SetOrAddProperty("DocumentLibrary", string.Empty);
            wrapperObject.SetOrAddProperty("FeaturedRank", "0");

            var contentItem = (((WrapperObject)wrapperObject.WrappedObject).WrappedObject) as IDynamicFieldsContainer ?? ((WrapperObject)((WrapperObject)((WrapperObject)wrapperObject.WrappedObject).WrappedObject).WrappedObject).WrappedObject as IDynamicFieldsContainer;
            //if (contentItem != null)
            //{
            //    var categories = contentItem.GetValue<IList<Guid>>("Category");
            //    if (categories != null)
            //    {
            //        //remove the "-" from the guid since it's difficult to search for a special character
            //        wrapperObject.SetOrAddProperty("CategoryIds", string.Join(" ", categories.Select(g => g.ToString().Replace("-", ""))));
            //    }
            //}
            var dataItem = (IDataItem)contentItem;

            #endregion

            StringBuilder sb = new StringBuilder();

            #region Link
            //set the link from the content location
            wrapperObject.SetOrAddProperty("Link", string.Empty);
            var contentLocation = SystemManager.GetContentLocationService().GetItemDefaultLocation(dataItem);
            var content         = contentItem.DoesFieldExist("Content") ? HttpUtility.HtmlDecode(contentItem.GetValue <Lstring>("Content").ToString().StripHtmlTags()) : null;

            if (content != null)
            {
                wrapperObject.SetOrAddProperty("Content", content);
            }
            else
            {
                wrapperObject.SetOrAddProperty("Content", "");
            }

            var source = contentItem.DoesFieldExist("SourceSite") ? contentItem.GetValue <string>("SourceSite") : null;

            if (string.IsNullOrWhiteSpace(content) && !string.IsNullOrWhiteSpace(source))
            {
                wrapperObject.SetProperty("Link", source);
            }
            else if (contentLocation != null)
            {
                wrapperObject.SetProperty("Link", contentLocation.ItemAbsoluteUrl);
            }
            else
            {
                try
                {
                    var clService = SystemManager.GetContentLocationService();

                    //gets the item default location of a given item by itemId provided
                    var location    = clService.GetItemDefaultLocation(dataItem);
                    var absoluteUrl = location.ItemAbsoluteUrl;
                    wrapperObject.SetProperty("Link", absoluteUrl);
                }
                catch (Exception)
                {
                    if (wrapperObject.GetProperty("ContentType").ToString().Contains("Dynamic"))
                    {
                        var dynamicContent = contentItem as DynamicContent;
                        wrapperObject.SetProperty("Link", dynamicContent.Urls.FirstOrDefault().Url);
                    }
                    else
                    {
                        wrapperObject.SetProperty("Link", string.Empty);
                    }
                }
            }
            #endregion

            #region Title

            //set the "SortTitle" as a uppercase string - sorting by title didn't work very well...
            var sortTitle = wrapperObject.GetProperty("Title").ToString().Trim().ToLower().GenerateSlug().Replace("-", "");
            //Log.Write(String.Format("pipe-title:{0}, link:{1}", sortTitle, ), ConfigurationPolicy.Debug);

            wrapperObject.SetOrAddProperty("SortTitle", sortTitle);

            #endregion

            #region Provider

            //set the name of the provider
            var provider = dataItem.Provider as DataProviderBase;
            wrapperObject.SetOrAddProperty("Provider", string.Empty);
            if (provider != null)
            {
                wrapperObject.SetProperty("Provider", provider.Name);
            }

            #endregion

            #region Categories

            //set the list of category ids
            wrapperObject.SetOrAddProperty("CategoryIds", string.Empty);
            wrapperObject.SetOrAddProperty("CategoryList", string.Empty);
            if (contentItem.DoesFieldExist("Category"))
            {
                var categories = contentItem.GetValue <IList <Guid> >("Category");
                if (categories != null)
                {
                    var categoryList = "";
                    //remove the "-" from the guid since it's difficult to search for a special character
                    var categoryIds = string.Join(" ", categories.Select(g => g.ToString().Replace("-", "")));
                    wrapperObject.SetOrAddProperty("CategoryIds", string.Join(" ", categories.Select(g => g.ToString().Replace("-", ""))));

                    foreach (var item in categories)
                    {
                        var category     = taxonomyManager.GetTaxon(item);
                        var categoryName = category.Title.Value;
                        categoryList = categoryList + "," + categoryName;
                    }

                    categoryList = categoryList.TrimStart(',');
                    wrapperObject.SetOrAddProperty("CategoryList", categoryList);
                }
            }

            //set the list of category ids
            wrapperObject.SetOrAddProperty("ResourceTypesIds", string.Empty);
            wrapperObject.SetOrAddProperty("ResourceTypesList", string.Empty);
            if (contentItem.DoesFieldExist("resourcetypes"))
            {
                var categories = contentItem.GetValue <IList <Guid> >("resourcetypes");
                if (categories != null)
                {
                    var categoryList = "";
                    //remove the "-" from the guid since it's difficult to search for a special character
                    wrapperObject.SetOrAddProperty("ResourceTypesIds", string.Join(" ", categories.Select(g => g.ToString().Replace("-", ""))));

                    foreach (var item in categories)
                    {
                        var category     = taxonomyManager.GetTaxon(item);
                        var categoryName = category.Title.Value;
                        categoryList = categoryList + "," + categoryName;
                    }

                    categoryList = categoryList.TrimStart(',');
                    wrapperObject.SetOrAddProperty("ResourceTypesList", categoryList);
                }
            }

            //set the list of category ids
            wrapperObject.SetOrAddProperty("OrganizationalAuthorsIds", string.Empty);
            wrapperObject.SetOrAddProperty("OrganizationalAuthorsList", string.Empty);
            if (contentItem.DoesFieldExist("organizationalauthors"))
            {
                var categories = contentItem.GetValue <IList <Guid> >("organizationalauthors");
                if (categories != null)
                {
                    var categoryList = "";
                    //remove the "-" from the guid since it's difficult to search for a special character
                    wrapperObject.SetOrAddProperty("OrganizationalAuthorsIds", string.Join(" ", categories.Select(g => g.ToString().Replace("-", ""))));

                    foreach (var item in categories)
                    {
                        var category     = taxonomyManager.GetTaxon(item);
                        var categoryName = category.Title.Value;
                        categoryList = categoryList + "," + categoryName;
                    }

                    categoryList = categoryList.TrimStart(',');
                    wrapperObject.SetOrAddProperty("OrganizationalAuthorsList", categoryList);
                }
            }

            #endregion

            #region Categories

            //set the list of category ids
            wrapperObject.SetOrAddProperty("DateField", string.Empty);
            if (contentItem.DoesFieldExist("Date"))
            {
                try
                {
                    if (contentItem.GetValue <DateTime>("Date") != null)
                    {
                        wrapperObject.SetOrAddProperty("DateField", contentItem.GetValue <DateTime>("Date").ToString());
                    }
                }
                catch (Exception ex)
                {
                }
            }

            #endregion


            #region Publication Date
            //set the "PublishDate" as a string - lucene will only order by strings
            var publicationDate = contentItem.GetValue <DateTime>("PublicationDate");
            wrapperObject.SetOrAddProperty("PublishDate", publicationDate.ToString());
            #endregion

            #region Image field
            wrapperObject.SetOrAddProperty("ImageId", "");
            wrapperObject.SetOrAddProperty("ImageUrl", "");
            if (contentItem.DoesFieldExist("Image"))
            {
                try
                {
                    var iDataItem = contentItem.GetValue <List <IDataItem> >("Image").FirstOrDefault();
                    if (iDataItem != null)
                    {
                        var image = LibrariesManager.GetManager().GetImages().FirstOrDefault(i => i.Id == iDataItem.Id);
                        if (image != null)
                        {
                            wrapperObject.SetOrAddProperty("ImageId", iDataItem.Id);
                            wrapperObject.SetOrAddProperty("ImageUrl", image.Urls.First().Url);
                        }
                    }
                }
                catch (Exception ex)
                {
                }
            }
            #endregion



            #region Blogs and Blog Posts

            //different blogs get different treatment
            wrapperObject.SetOrAddProperty("ThumbnailUrl", string.Empty);
            if (wrapperObject.GetProperty("ContentType").ToString().Contains("BlogPost"))
            {
                var post   = (BlogPost)contentItem;
                var parent = post.Parent;
                if (parent.Id != null)
                {
                    wrapperObject.SetOrAddProperty("DocumentLibrary", parent.Title.Value);
                }
                else
                {
                    wrapperObject.SetOrAddProperty("DocumentLibrary", "Blog");
                }

                if (contentItem.DoesFieldExist("ThumbnailUrl"))
                {
                    wrapperObject.SetOrAddProperty("ThumbnailUrl", post.GetValue <string>("ThumbnailUrl"));
                }

                //try
                //{
                //    var featured = post.GetValue<Boolean>("Featured");
                //    if (featured)
                //    {
                //        wrapperObject.SetOrAddProperty("FeaturedRank", "1");
                //    }
                //}
                //catch (Exception)
                //{
                //}

                content = post.Content.ToString().StripHtmlTags();
                wrapperObject.SetOrAddProperty("Content", content);
            }

            #endregion

            #region News

            //different blogs get different treatment
            if (wrapperObject.GetProperty("ContentType").ToString().Contains("News"))
            {
                wrapperObject.SetOrAddProperty("DocumentLibrary", "News");
            }

            #endregion

            #region Event

            wrapperObject.SetOrAddProperty("EventStart", string.Empty);
            wrapperObject.SetOrAddProperty("EventEnd", string.Empty);
            wrapperObject.SetOrAddProperty("LocationStreet", string.Empty);
            wrapperObject.SetOrAddProperty("LocationState", string.Empty);
            wrapperObject.SetOrAddProperty("LocationCity", string.Empty);
            wrapperObject.SetOrAddProperty("Selfpaced", "False");

            if (contentItem.DoesFieldExist("EventStart"))
            {
                wrapperObject.SetOrAddProperty("DocumentLibrary", "Events");

                var eventStart = contentItem.GetValue <DateTime?>("EventStart");
                var eventEnd   = contentItem.GetValue <DateTime?>("EventEnd");
                var street     = contentItem.DoesFieldExist("Street") ? !contentItem.GetValue <Lstring>("Street").Value.IsNullOrEmpty() ? contentItem.GetValue <Lstring>("Street").Value : "" : "";
                var state      = contentItem.DoesFieldExist("State") ? !contentItem.GetValue <Lstring>("State").Value.IsNullOrEmpty() ? contentItem.GetValue <Lstring>("State").Value : "" : "";
                var city       = contentItem.DoesFieldExist("City") ? !contentItem.GetValue <Lstring>("City").Value.IsNullOrEmpty() ? contentItem.GetValue <Lstring>("City").Value : "" : "";
                var selfPaced  = contentItem.DoesFieldExist("Selfpaced") ? contentItem.GetValue <bool>("Selfpaced") ? "True" : "False" : "False";

                wrapperObject.SetOrAddProperty("Selfpaced", selfPaced);

                if (eventStart.HasValue)
                {
                    wrapperObject.SetProperty("EventStart", eventStart.Value.ToLocalTime().ToString());
                    wrapperObject.SetProperty("PublicationDate", eventStart.Value.ToLocalTime().ToString());
                }

                if (eventEnd.HasValue)
                {
                    wrapperObject.SetProperty("EventEnd", eventEnd.Value.ToLocalTime().ToString());
                }

                if (!street.IsNullOrEmpty())
                {
                    wrapperObject.SetOrAddProperty("LocationStreet", street);
                }

                if (!state.IsNullOrEmpty())
                {
                    wrapperObject.SetOrAddProperty("LocationState", state);
                }

                if (!city.IsNullOrEmpty())
                {
                    wrapperObject.SetOrAddProperty("LocationCity", city);
                }
            }

            #endregion

            #region Documents

            //index the content of attached files
            wrapperObject.SetOrAddProperty("DocumentText", string.Empty);
            wrapperObject.SetOrAddProperty("DocumentLink", string.Empty);
            if (wrapperObject.GetProperty("ContentType").ToString().Contains("Document"))
            {
                var librariesManager = LibrariesManager.GetManager();
                var service          = ServiceBus.ResolveService <IDocumentService>();
                var document         = librariesManager.GetDocument(Guid.Parse(wrapperObject.GetProperty("Id").ToString()));
                var documentLibrary  = document.Library;
                wrapperObject.SetOrAddProperty("DocumentLink", document.MediaUrl);
                wrapperObject.SetOrAddProperty("DocumentLibrary", documentLibrary.Title.Value);

                try
                {
                    var stream  = BlobStorageManager.GetManager(document.GetStorageProviderName()).GetDownloadStream(document);
                    var pdfText = service.ExtractText(document.MimeType, stream);

                    wrapperObject.SetOrAddProperty("DocumentText", pdfText.Trim());
                }
                catch (Exception ex)
                {
                    //log the error, but don't stop the index
                    LogManager.GetCurrentClassLogger().Warn(ex);
                }
            }

            #endregion

            #region DynamicContent

            wrapperObject.SetOrAddProperty("DisplayDate", string.Empty);
            //different blogs get different treatment
            if (wrapperObject.GetProperty("ContentType").ToString().Contains("Dynamic"))
            {
                var dynamicType = wrapperObject.GetProperty("ContentType").ToString().Split('.').Last();
                wrapperObject.SetOrAddProperty("DocumentLibrary", dynamicType);
            }

            if (wrapperObject.GetProperty("ContentType").ToString().Contains("PressRelease"))
            {
                var dynamicContent = contentItem as DynamicContent;
                content = dynamicContent.GetValue <Lstring>("Body").ToString().StripHtmlTags();
                wrapperObject.SetOrAddProperty("Content", content);

                //var featured = dynamicContent.GetValue<Boolean>("Featured");
                //if (featured)
                //{
                //    wrapperObject.SetOrAddProperty("FeaturedRank", "1");
                //}

                content = dynamicContent.GetValue <Lstring>("Body").ToString().StripHtmlTags();
            }

            if (wrapperObject.GetProperty("ContentType").ToString().Contains("OnSceneArticles.OnSceneArticle"))
            {
                var dynamicContent = contentItem as DynamicContent;
                content = dynamicContent.GetValue <Lstring>("Body").ToString().StripHtmlTags();
                wrapperObject.SetOrAddProperty("Content", content);

                //var featured = dynamicContent.GetValue<Boolean>("Featured");
                //if (featured)
                //{
                //    wrapperObject.SetOrAddProperty("FeaturedRank", "1");
                //}
                var displayDate = dynamicContent.GetValue <Lstring>("DisplayDate").Value;
                if (!displayDate.IsNullOrWhitespace())
                {
                    wrapperObject.SetOrAddProperty("DisplayDate", displayDate);
                }
            }

            if (wrapperObject.GetProperty("ContentType").ToString().Contains(".Resources.Resource"))
            {
                var dynamicContent = contentItem as DynamicContent;
                content = dynamicContent.GetValue <Lstring>("Article").ToString().StripHtmlTags();
                wrapperObject.SetOrAddProperty("Content", content);

                //var featured = dynamicContent.GetValue<Boolean>("Featured");
                //if (featured)
                //{
                //    wrapperObject.SetOrAddProperty("FeaturedRank", "1");
                //}

                content = dynamicContent.GetValue <Lstring>("Article").ToString().StripHtmlTags();
            }

            if (wrapperObject.GetProperty("ContentType").ToString().Contains(".LegacyIndustryArticles.LegacyIndustryArticle"))
            {
                var dynamicContent = contentItem as DynamicContent;
                content = dynamicContent.GetValue <Lstring>("Body").ToString().StripHtmlTags();
                wrapperObject.SetOrAddProperty("Content", content);

                //var featured = dynamicContent.GetValue<Boolean>("Featured");
                //if (featured)
                //{
                //    wrapperObject.SetOrAddProperty("FeaturedRank", "1");
                //}
            }

            if (wrapperObject.GetProperty("ContentType").ToString().Contains(".DossierArticles.DossierArticle"))
            {
                var dynamicContent = contentItem as DynamicContent;
                content = dynamicContent.GetValue <Lstring>("Body").ToString().StripHtmlTags();
                wrapperObject.SetOrAddProperty("Content", content);

                //var featured = dynamicContent.GetValue<Boolean>("Featured");
                //if (featured)
                //{
                //    wrapperObject.SetOrAddProperty("FeaturedRank", "1");
                //}
            }

            #endregion

            #region Resources

            //different blogs get different treatment
            if (wrapperObject.GetProperty("ContentType").ToString().Contains("Resources.Resource"))
            {
                try
                {
                    var iDataItem = contentItem.GetValue <List <IDataItem> >("featuredimage").FirstOrDefault();
                    if (iDataItem != null)
                    {
                        var image = LibrariesManager.GetManager().GetImages().FirstOrDefault(i => i.Id == iDataItem.Id);
                        if (image != null)
                        {
                            wrapperObject.SetOrAddProperty("ImageId", iDataItem.Id);
                            wrapperObject.SetOrAddProperty("ImageUrl", image.Urls.First().Url);
                        }
                    }
                }
                catch (Exception ex)
                {
                }
            }

            #endregion



            #region Pages

            if (wrapperObject.HasProperty("Page"))
            {
                wrapperObject.SetOrAddProperty("DocumentLibrary", "Page");

                //value looks like this in DB: "0619909c-4174-6fcd-88ea-ff000002c0f4;Policy & Initiatives > Policy Topics > Accessibility & Disability"
                var pageValue = wrapperObject.GetProperty("Page");

                if (pageValue != null)
                {
                    var pageId        = Guid.Parse(pageValue.ToString().Split(';').First());
                    var pageManager   = PageManager.GetManager();
                    var pageNode      = pageManager.GetPageNode(pageId);
                    var pageData      = pageManager.GetPageDataList().First(d => d.Id == pageNode.PageId);
                    var contentBlocks = pageData.Controls.Where(c => c.ObjectType == typeof(ContentBlock).FullName);
                    var contentText   = string.Join(" ", contentBlocks.Select(c => ((ContentBlock)pageManager.LoadControl(c)).Html.StripHtmlTags()));

                    wrapperObject.SetOrAddProperty("Content", contentText);
                    wrapperObject.SetOrAddProperty("Link", pageNode.GetFullUrl());
                    wrapperObject.SetOrAddProperty("Title", pageNode.Title);
                }
            }

            #endregion

            #region Infographics

            if (wrapperObject.GetProperty("ContentType").ToString().Contains("Infographics"))
            {
                var dynamicManager  = DynamicModuleManager.GetManager();
                var infographicType = TypeResolutionService.ResolveType("Telerik.Sitefinity.DynamicTypes.Model.Infographics.Infographics");
                var id          = Guid.Parse(wrapperObject.GetProperty("Id").ToString());
                var item        = dynamicManager.GetDataItem(infographicType, id);
                var contentLink = item.GetValue <ContentLink[]>("Image");
                if (contentLink != null && contentLink.Any())
                {
                    var librariesManager = LibrariesManager.GetManager();
                    var image            = librariesManager.GetImage(contentLink.First().ChildItemId);
                    wrapperObject.SetOrAddProperty("ThumbnailUrl", image.MediaUrl);
                }
            }

            #endregion


            #region Resource Library Information

            //map a few columns for types
            var objectType = ResourceLibraryHelper.SearchTypes.FirstOrDefault(i => i.Item2 == (string)wrapperObject.GetProperty("DocumentLibrary"));
            wrapperObject.SetOrAddProperty("ContentTypeName", string.Empty);
            wrapperObject.SetOrAddProperty("ContentTypeOrdinal", string.Empty);
            if (objectType != null)
            {
                wrapperObject.SetOrAddProperty("ContentTypeName", objectType.Item1);
                wrapperObject.SetOrAddProperty("ContentTypeOrdinal", objectType.Item3.ToString("000"));
            }
            else
            {
                wrapperObject.SetOrAddProperty("ContentTypeName", "Unsorted");
                wrapperObject.SetOrAddProperty("ContentTypeOrdinal", "100");
            }

            #endregion

            return(base.GetConvertedItemsForMapping(wrapperObject));
        }
        public void ProcessData()
        {
            try
            {
                Utility.Log("PI server : " + ConfigurationSettings.PiServer);
                Utility.Log("Azure ConnectionString : " + ConfigurationSettings.AzureConnectionString);
                Utility.Log("Pi Server ConnectionString : " + ConfigurationSettings.PiServerConnectionString);

                if (!((string.IsNullOrEmpty(ConfigurationSettings.PiServer)) || (string.IsNullOrEmpty(ConfigurationSettings.AzureConnectionString)) || (string.IsNullOrEmpty(ConfigurationSettings.PiServerConnectionString))
                      ))
                {
                    Console.WriteLine("Init ProcessData");
                    Utility.Log("Init ProcessData");
                    if (utcConversionTime != GetAndTimezone())
                    {
                        utcConversionTime = GetAndTimezone();
                        PIConfigurationInfoModel piConfig = new PIConfigurationInfoModel();
                        string serverName = ConfigurationSettings.PiServer;
                        piConfig.PiServerDesc      = serverName;
                        piConfig.PiServerName      = serverName;
                        piConfig.PiServerURL       = ConfigurationSettings.PiServerConnectionString;
                        piConfig.UTCConversionTime = utcConversionTime;
                        piConfig.CreatedOn         = DateTime.UtcNow;
                        ConnectionManager.Instance().InserPIConfigurationDetailsToDB(piConfig);
                    }
                    ConnectionManager.Instance().Initialize();
                    Console.WriteLine("Done with Console manager initialization");

                    string storageConnectionString = ConfigurationSettings.GetCloudConfigDataModel().BlobStorageURL;
                    //patch for now

                    storageConnectionString = ConfigurationSettings.StorageConnectionString;

                    //
                    if (!string.IsNullOrEmpty(storageConnectionString))
                    {
                        BlobStorageManager.Instance().ConfigureBlobStorage(storageConnectionString);
                        Console.WriteLine("Done with Blob Storage configuration");
                        Utility.Log("Done with Console manager initialization");

                        string piServer = ConnectionManager.Instance().GetPIServer();


                        Thread piThread = new Thread(() => { ProcessDataByPIServer(piServer); });
                        piThread.Start();
                        //Thread sensorThread = new Thread(() => { InsertSensorData(piServer); });
                        //sensorThread.Start();
                    }
                    else
                    {
                        Utility.Log("Does not have storage connection string ");
                    }
                }
                else
                {
                    Console.WriteLine("Doesn't have sufficient data in app config for connection");
                    Console.ReadLine();
                    Utility.Log("Doesn't have sufficient data in app config for connection");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error occured in processData" + e.Message);
                Utility.Log("Error occured in processData" + e.Message);
            }
        }
Exemple #29
0
        private async Task <bool> CreateContainer(string containerName, IDictionary <string, string> metaData, CancellationToken cancellationToken = default)
        {
            BlobContainerClient containerClient = BlobStorageManager.GetBlobContainerClient(_azureStorageOptions, containerName.ToLower());

            return(await Task.FromResult(containerClient != null));
        }