<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mehmet Yener YILMAZ on Medium]]></title>
        <description><![CDATA[Stories by Mehmet Yener YILMAZ on Medium]]></description>
        <link>https://medium.com/@myeneryilmaz?source=rss-f86b422cc3a9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5ZUJFQhPQnDOJnyESwcnlA.jpeg</url>
            <title>Stories by Mehmet Yener YILMAZ on Medium</title>
            <link>https://medium.com/@myeneryilmaz?source=rss-f86b422cc3a9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 03:10:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@myeneryilmaz/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[ChatGPT sdk integration to .Net Core]]></title>
            <link>https://medium.com/geekculture/chatgpt-sdk-integration-to-net-core-3b1b74ca1739?source=rss-f86b422cc3a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b1b74ca1739</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[net-core-6]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Mehmet Yener YILMAZ]]></dc:creator>
            <pubDate>Fri, 07 Apr 2023 08:50:25 GMT</pubDate>
            <atom:updated>2023-04-08T07:58:25.830Z</atom:updated>
            <content:encoded><![CDATA[<h3>ChatGPT client integration to .Net Core Web API</h3><p>First of first, if you think like “Why do I read your article when ChatGPT explains how to integrate itself anyway?” you absolutely right.🤣 ChatGPT is smart enough to make this for you in the first place</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*aPgUSdS58Hl4ae3pYz_bSQ.png" /></figure><p>But with <strong>one important difference</strong>, it shows implementation via OpenAPI client which is fine but not a GPT package. in this sample, I will go with the <a href="https://github.com/betalgo/openai">Betalgo</a> package which is another open-source but enriched and battle-tested lib for GPT3 specifically built on top of OpenAPI.</p><p><a href="https://graphemica.com/%E2%9A%A0">⚠</a><em> Note: There is no official GPT SDK for .Net at the moment</em></p><p>You can follow up these steps;</p><ol><li>Create a new Asp.net web application and go to the NuGet package manager to download Betalgo.OpenAI.GPT3 or open the package manager console and run this command: Install-Package Betalgo.OpenAI.GPT3</li><li>Go to <a href="https://openai.com/api/">https://openai.com/api/</a> and sign in with your account</li><li>Click “View API Keys” under the profile settings dropdown at the top right and click “Create new secret key”.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A1lEfSqlPZG3qg0n0WCt1Q.png" /><figcaption>I already created an API key</figcaption></figure><p>4. Go to the appsettings.json file and paste your secret key as seen below</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9ca71889379d216897a985d46e801a1/href">https://medium.com/media/e9ca71889379d216897a985d46e801a1/href</a></iframe><p>5. Go to Program.cs file and copy-paste the content below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6a3c69bee7a0e51d0683fe74c423a02/href">https://medium.com/media/d6a3c69bee7a0e51d0683fe74c423a02/href</a></iframe><p>6. Go to the controller file and copy-paste the content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fd0b71b4dd766731618e8bbe7e255dc/href">https://medium.com/media/8fd0b71b4dd766731618e8bbe7e255dc/href</a></iframe><p>That’s it, this is all you need to set up ready to go basic chatbot app powered by ChatGPT. You can access the source code via the link <a href="https://github.com/y3n3rrr/ChatgptAPI">here</a>. There might be new incoming features for OpenAIService, and I probably will edit this app along with new releases by the OpenAI team.</p><p>Thanks for reading, <br>Farewell.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b1b74ca1739" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/chatgpt-sdk-integration-to-net-core-3b1b74ca1739">ChatGPT sdk integration to .Net Core</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Anomaly Detection and Prediction using ML.Net TimeSeries library]]></title>
            <link>https://medium.com/geekculture/anomaly-detection-and-prediction-using-ml-net-timeseries-library-e91838ca0ba3?source=rss-f86b422cc3a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e91838ca0ba3</guid>
            <category><![CDATA[anomaly-detection]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mlnet]]></category>
            <dc:creator><![CDATA[Mehmet Yener YILMAZ]]></dc:creator>
            <pubDate>Thu, 13 May 2021 12:57:11 GMT</pubDate>
            <atom:updated>2021-05-15T20:48:06.025Z</atom:updated>
            <content:encoded><![CDATA[<p>There are many ways to leverage Artificial Intelligence in software services especially in business intelligence. The machine learning library of Microsoft, ML.Net has many algorithms its capabilities getting better day by day to help us to drive on these ways. Anomaly detection is one of the most important and frequently used of these techniques.</p><p><strong><em>What is anomaly detection?<br></em></strong>In data analysis, anomaly detection is the identification of rare items, events, or observations that raise suspicions by differing significantly from the majority of the data. It’s commonly used for;</p><ul><li>Fraud detection</li><li>Systems health monitoring</li><li>Event detection in sensor networks</li><li>Ecosystem disturbances</li><li>Data cleaning</li><li>Intrusion detection</li></ul><p>We gonna detect anomalies over time-series data of BitCoin prices by using the prediction algorithms of Microsoft.ML.TimeSeries</p><p><strong><em>What is time-series data?<br></em></strong>Time series data means the data that is captured at a specific range of time such as a company’s stock price, transactions of a bank account, etc. these are classic examples of time series data. <br>In our particular case, this will be Bitcoin prices last 180 days and we gonna use these data to train our model to detect anomalies and predict prices in future</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OJsrNiTzZFKy3Z8w4jd3Yw.png" /><figcaption>Bitcoin chart that shows fluctuations in the last 12 months</figcaption></figure><blockquote><a href="https://graphemica.com/%E2%9A%A0">⚠</a> Caution: In real life there are tremendous parameters that affect Bitcoin prices and it&#39;s impossible to process wih AI. We will only reference prices in last 6 months. And our model will say samething based on only numbers. So never ever put your real money in any kind of application out there that claims its capable of doing this</blockquote><p>We should follow up these steps to develop the application;</p><p>🛈 Let me say, these steps below explain why we do that briefly but if you want to skip the puzzle and download source code feel free to go end of the article.</p><ol><li>First, we need to gather BitCoin data that will be used for training our network. Go to <a href="https://coinmarketcap.com/">https://coinmarketcap.com</a> and click BitCoin then <a href="https://coinmarketcap.com/currencies/bitcoin/historical-data/">Historical Data</a> tab. You will see a data grid that lists the records of prices in the selected range of dates. Its such a shame there is no export as a file option there, well they dont assume someone might be in need of it :)<br>so we need to copy it. Anway select `Date Range` and `Last 180 days` copy paste data including headers(Btw coinmarketcap also provides developer APIs to share resources but it&#39;s out of topic)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ni4LYBF2Y_iYZQNdzJlrVA.png" /><figcaption>Our training data source is <a href="https://coinmarketcap.com/currencies/bitcoin/historical-data/">https://coinmarketcap.com/currencies/bitcoin/historical-data/</a></figcaption></figure><p>2. Create an empty .Net Core console application and check Place solution and project in the same directory` then click next to select SDK, this sample works fine with v3.1 too, but I will go with .NET 5.0 which is the latest version of .net core</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*IIDWBgFcIyFT6f1lLMS7gw.png" /></figure><p>Then create an empty CSV file and paste data from coinmarketcap into it.<br>Don&#39;t forget to format the date, this is required our app to read the data in the file</p><p>Select the date column and Format Cells-&gt; Date -&gt; *3/14/2012 then select all of the others Format Cells-&gt; Currency -&gt; 1,234.10 click ok then format the same currency columns again Format Cells-&gt; Currency -&gt; Use 1000 Seperator(,) now we are done. <br>File content should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*GS-tbH8QkO6qb3-zhIqJIw.png" /><figcaption>Dont forget to format data otherwise you gonna encounter an error during loading data to model</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*aAqIkaPQNsoJlBkB9CjLgA.png" /></figure><p>Flip back to VS, We need 2 libraries and we can install them via NuGet package manager. These are <strong>Microsoft.ML</strong> and <strong>Microsoft.ML.TimeSeries.</strong> Your project solution should look like this at his point.</p><p>In the first section, we gonna cover Anomaly Detection then Price Prediction over given data. Before that, we should read data from the file, let&#39;s start writing code: Create an MLContext instance and load the contents of the target file. This is what we should do to achieve that;</p><pre>var context = new MLContext();<br>var data = context.Data.LoadFromTextFile&lt;CurrencyModel&gt;(targetFile, hasHeader: true, separatorChar: ‘,’);</pre><p>Next, create an estimator to detect anomalies, we will use Singular Spectrum Analysis inside Transforms Catalog of ML Context and transform data desired to shape:</p><pre>var pipelineAnomaly = context.Transforms.DetectSpikeBySsa(nameof(SpikeAnomaly.Anomalies),nameof(CurrencyModel.Close), confidence: 98.0,trainingWindowSize: 90, seasonalityWindowSize: 30, pvalueHistoryLength: 20);<br>var transformedData = pipelineAnomaly.Fit(data).Transform(data);</pre><p>🛈 I have detected anomalies over “<em>Close</em>” prices over bitcoin which indicates is final prices on the day. If you want to detect <em>Highest </em>or <em>Lowest </em>prices, simply change this column as you wish it&#39;s must be the same as the target data column name.</p><p>Finally create a list to store detected anomalies:</p><pre>var anomalies = context.Data.CreateEnumerable&lt;SpikeAnomaly&gt;(transformedData, reuseRowObject: false).ToList();</pre><p>Then write to console detected anomalies of given data:</p><pre>var prices = data.GetColumn&lt;float&gt;(&quot;Close&quot;).ToArray();<br>var dates = data.GetColumn&lt;DateTime&gt;(&quot;Date&quot;).ToArray();<br>for (int i = 0; i &lt; anomalies.Count; i++) {<br>   if (anomalies[i].Anomalies[0] == 1) {<br>      Console.WriteLine($&quot;{dates[i]}\t{prices[i]}&quot;);<br>   }<br>}</pre><p>That&#39;s it, now run the application to see if it&#39;s working as expected, you suppose to see a window look like this;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*J49CJdpgR3pDFBS4GaVfvQ.png" /></figure><p>That&#39;s all for anomaly detection now let&#39;s begin the second section <br>Price Prediction: <br>We already loaded data to ML context so we only need to create a new estimator via forecasting singular spectrum analysis(SSA) function and create a model;</p><pre>var pipelinePrediction = context.Forecasting.ForecastBySsa(nameof(PricePrediction.Predictions), nameof(CurrencyModel.Close), windowSize: 5, seriesLength: 10, trainSize: 100, horizon: 2); <br>var model = pipelinePrediction.Fit(data);</pre><p>Then create a prediction engine for the time series pipeline and call prediction function. You can also define the number of predictions that will be calculated. In our case, it will be 3, so the next 3 days of bitcoin prices will be predicted by using the prediction engine.</p><pre>var forecastContext = model.CreateTimeSeriesEngine&lt;CurrencyModel, PricePrediction&gt;(context); <br>var forecasts = forecastContext.Predict(3); // Predict prices in next 3 days<br>foreach (var item in forecasts.Predictions) {     <em> </em>  Console.WriteLine(item); <br>}</pre><p>The parameter in Predictfunctions indicate the number of prediction will be calculated by the engine. In our case, we want to see the next 3 days. After this step your code solution file should look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dMmsOhsZDLSbY-3-rHzjsA.png" /></figure><p>Let&#39;s run the project and see how it&#39;s working.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*1tGuZrvRijyaICRW_1UfsA.png" /></figure><p>If you see something like this on your console, that&#39;s it. Our anomaly detection and prediction over the given file contains bitcoin prices(data.csv) works very well 🤘</p><p>This is all I want to share in this article. You can download the full <a href="https://github.com/y3n3rrr/AnomalyDetectionSample">source code here</a> and run or improve the project by yourself. If you have any questions drop a comment in the section below. Wish you all happy and healthy days!</p><p>Farewell,<br>Mehmet Yener YILMAZ</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e91838ca0ba3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/anomaly-detection-and-prediction-using-ml-net-timeseries-library-e91838ca0ba3">Anomaly Detection and Prediction using ML.Net TimeSeries library</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Emotion Analysis with building an Artificial Neural Network using ML.NET powered by Tensorflow]]></title>
            <link>https://medium.com/analytics-vidhya/emotion-analysis-with-building-an-artificial-neural-network-using-ml-net-powered-by-tensorflow-dd08aeb9aad7?source=rss-f86b422cc3a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd08aeb9aad7</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[mlnet]]></category>
            <dc:creator><![CDATA[Mehmet Yener YILMAZ]]></dc:creator>
            <pubDate>Fri, 11 Dec 2020 19:16:35 GMT</pubDate>
            <atom:updated>2023-11-11T18:20:07.130Z</atom:updated>
            <content:encoded><![CDATA[<h3>Emotion Analysis with building an Artificial Neural Network using ML.NET with Tensorflow</h3><p>Machine learning and AI are new shining lights on information technology. Microsoft, as one of the biggest market sharer of IT finally announced ML.NET in May 2018 to aid .Net developers to achieve their goals. But it’s quite new and compared to other technologies such as Python, Java, LISP, etc. there aren’t yet enough sources in terms of open source projects, libraries, or 3rd tools. There is still a long way to go for .Net to catch up with other big techs to grow its community</p><p>Fortunately, we don&#39;t have to wait until this happens, thanks to Microsoft Engineers they make ML.NET comes up with an adaptive development experience and supports <a href="https://en.wikipedia.org/wiki/Python_(programming_language)">Python</a> models when used together with NimbusML. <br>We all should appreciate Microsoft for amazing work!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*FWFN3hFVYuuIB2CQSpdZBg.gif" /></figure><p>Some fellows prefer watching instead of reading, also making a video to demonstrate this kind of stuff in action often makes sense, the existence of the video below just because of that.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F6SmCATYKsuE%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D6SmCATYKsuE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F6SmCATYKsuE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/25cab25e0ea4f249b625ce20d0eb1861/href">https://medium.com/media/25cab25e0ea4f249b625ce20d0eb1861/href</a></iframe><p>In our project, we will be using an existing pre-trained Tensorflow model which build by a neural network with thousands of images and lives in one of Google’s server and get leverage of<strong> </strong><a href="https://en.wikipedia.org/wiki/Deep_learning"><strong>deep learning</strong></a> to build our own neural network to improve our accuracy and speed up the training process. I will create a .Net Core Console application to implement this and when it comes to the end of the article we will have a cross-platform executable application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*NZ_u3dMeTqh31q2pN9GNQQ.png" /><figcaption>The image above represents the topology of an ML.NET application</figcaption></figure><p>Let me say, this article strongly inspired by <a href="https://github.com/dotnet/machinelearning-samples/tree/master/samples/csharp/getting-started/DeepLearning_TensorFlowEstimator">this</a> official documentation of Microsoft. Enough of talking let&#39;s step into action.</p><p>I have changed the input data set and included helper methods,<br>Finally, for the sake of accuracy, standardized the models by reformatted and grayscaled each image, some example of placed below;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*a9rHxs6184R3mRojdmBK_g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/785/1*PSMBUAS86qRllwvaS0aaEA.png" /></figure><p>This editing is so simple thanks to .Net Core Image Processing library which comes up with System.Drawing namespace, what we do with it is first just resize the image to 48x48 then convert to grayscale. These codes below satisfy our needs gracefully;</p><pre>public static Bitmap TranformToGrayscale(Bitmap original)<br>        {<br>            //create a blank bitmap the same size as original<br>            Bitmap newBitmap = new Bitmap(original.Width, original.Height);</pre><pre>//get a graphics object from the new image<br>            using (Graphics g = Graphics.FromImage(newBitmap))<br>            {<br>                //create the grayscale ColorMatrix<br>                System.Drawing.Imaging.ColorMatrix colorMatrix = new System.Drawing.Imaging.ColorMatrix(<br>                   new float[][]<br>                   {<br>             new float[] {.3f, .3f, .3f, 0, 0},<br>             new float[] {.59f, .59f, .59f, 0, 0},<br>             new float[] {.11f, .11f, .11f, 0, 0},<br>             new float[] {0, 0, 0, 1, 0},<br>             new float[] {0, 0, 0, 0, 1}<br>                   });</pre><pre>//create some image attributes<br>                using (ImageAttributes attributes = new ImageAttributes())<br>                {<br>                    //set the color matrix attribute<br>                    attributes.SetColorMatrix(colorMatrix);</pre><pre>//draw the original image on the new image<br>                    //using the grayscale color matrix<br>                    g.DrawImage(original, new System.Drawing.Rectangle(0, 0, original.Width, original.Height),<br>                                0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes);<br>                }<br>            }<br>            return newBitmap;<br>        }</pre><pre>public static Bitmap ResizeImage(System.Drawing.Image image, int width, int height)<br>        {<br>            var destRect = new System.Drawing.Rectangle(0, 0, width, height);<br>            var destImage = new Bitmap(width, height);</pre><pre>destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);</pre><pre>using (var graphics = Graphics.FromImage(destImage))<br>            {<br>                graphics.CompositingMode = CompositingMode.SourceCopy;<br>                graphics.CompositingQuality = CompositingQuality.HighQuality;<br>                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;<br>                graphics.SmoothingMode = SmoothingMode.HighQuality;<br>                graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;</pre><pre>using (var wrapMode = new ImageAttributes())<br>                {<br>                    wrapMode.SetWrapMode(WrapMode.TileFlipXY);<br>                    graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);<br>                }<br>            }</pre><pre>return destImage;<br>        }To improve the accuracy of our model we standardize images as greyscaled and 48x48 length no matter the size of the original image</pre><p>This removes noise from data as well as speeds up the training process and executes prediction faster.</p><p>We gonna follow up with these steps to make it work:</p><h3>1. Build Model</h3><p>Building the model includes the following steps:</p><ul><li>Load the image paths and related labels from the folders in the initial DataView</li><li>Load the Images in-memory while transforming as needed by the TensorFlow pre-trained model used, such as InceptionV3. (resize and normalize pixel values, as required by the deep neural network used)</li><li>Image <em>featurization</em> using the deep neural network model</li><li>Image classification using LbfgsMaximumEntropy</li></ul><p>Not: You can access the database of pre-trained Tensorflow models <a href="https://www.tensorflow.org/resources/models-datasets">here</a></p><p>Define the schema of data in a class type and refer to that type while loading data using TextLoader. Here the class type is ImageNetData.</p><pre>public class ImageData<br>    {<br>        [LoadColumn(0)]<br>        public string ImagePath;</pre><pre>        [LoadColumn(1)]<br>        public string Label;<br>    }</pre><p>Load all the training and test images into DataViews respectively by using the utility method by LoadImagesFromDirectory():</p><pre>IEnumerable&lt;ImageData&gt; allImages = LoadImagesFromDirectory(folder: imagesDownloadFolderPath, useFolderNameasLabel: true);</pre><pre>IEnumerable&lt;ImageData&gt; testImages = LoadImagesFromDirectory(folder: testimagesDownloadFolderPath);</pre><p>Shuffle the images so the dataset will be better balanced by label classes before splitting into two datasets: Training and Test datasets.</p><pre>ConsoleHelper.ConsoleWriteHeader(&quot;Read model&quot;);<br>Console.WriteLine($&quot;Model location: {inputTensorFlowModelFilePath}&quot;);<br>Console.WriteLine($&quot;Training file: {dataLocation}&quot;);</pre><pre>// 1. Load images information (filenames and labels) in IDataView</pre><pre>//Load the initial single full Image-Set<br>IDataView fullImagesDataset = mlContext.Data.LoadFromEnumerable(imageSet);<br>IDataView trainDataView = mlContext.Data.ShuffleRows(fullImagesDataset);<br>IDataView testDataView = mlContext.Data.LoadFromEnumerable(testSet);</pre><p>The following step defines the training pipeline. Usually, when dealing with deep neural networks, you must adapt the images to the format expected by the network. This is the reason images are resized and then transformed.</p><pre>// 2. Load images in-memory while applying image transformations <br>// Input and output column names have to coincide with the input and output tensor names of the TensorFlow model<br>// You can check out those tensor names by opening the Tensorflow .pb model with a visual tool like Netron: <a href="https://github.com/lutzroeder/netron">https://github.com/lutzroeder/netron</a><br>// TF .pb model --&gt; input node --&gt; INPUTS --&gt; input --&gt; id: &quot;input&quot; <br>// TF .pb model --&gt; Softmax node --&gt; INPUTS --&gt; logits --&gt; id: &quot;softmax2_pre_activation&quot; (Inceptionv1) or &quot;InceptionV3/Predictions/Reshape&quot; (Inception v3)</pre><pre>var dataProcessPipeline = mlContext.Transforms.Conversion.MapValueToKey(outputColumnName: LabelAsKey, inputColumnName: &quot;Label&quot;)<br>                .Append(mlContext.Transforms.LoadImages(outputColumnName: &quot;image_object&quot;, imageFolder: imagesFolder, inputColumnName: nameof(DataModels.ImageData.ImagePath)))<br>                .Append(mlContext.Transforms.ResizeImages(outputColumnName: &quot;image_object_resized&quot;, <br>                                                            imageWidth: ImageSettingsForTFModel.imageWidth, imageHeight: ImageSettingsForTFModel.imageHeight, <br>                                                            inputColumnName: &quot;image_object&quot;))<br>                .Append(mlContext.Transforms.ExtractPixels(outputColumnName:&quot;input&quot;, inputColumnName:&quot;image_object_resized&quot;, <br>                                                            interleavePixelColors:ImageSettingsForTFModel.channelsLast, <br>                                                            offsetImage:ImageSettingsForTFModel.mean, <br>                                                            scaleImage:ImageSettingsForTFModel.scale))  //for Inception v3 needs scaleImage: set to 1/255f. Not needed for InceptionV1. <br>                .Append(mlContext.Model.LoadTensorFlowModel(inputTensorFlowModelFilePath).<br>                        ScoreTensorFlowModel(outputColumnNames: new[] { &quot;InceptionV3/Predictions/Reshape&quot; }, <br>                                            inputColumnNames: new[] { &quot;input&quot; }, <br>                                            addBatchDimensionInput: false));  // (For Inception v1 --&gt; addBatchDimensionInput: true)  (For Inception v3 --&gt; addBatchDimensionInput: false)</pre><p>Finally, add the ML.NET classification trainer (LbfgsMaximumEntropy) to finalize the training pipeline:</p><pre>// Set the training algorithm and convert back the key to the categorical values (original labels)                            <br>var trainer = mlContext.MulticlassClassification.Trainers.LbfgsMaximumEntropy(labelColumnName: LabelAsKey, featureColumnName: &quot;InceptionV3/Predictions/Reshape&quot;);  //&quot;softmax2_pre_activation&quot; for Inception v1<br>var trainingPipeline = dataProcessPipeline.Append(trainer)<br>                                            .Append(mlContext.Transforms.Conversion.MapKeyToValue(PredictedLabelValue, &quot;PredictedLabel&quot;));</pre><h3>2. Train model</h3><p>In order to begin the training execute Fit on the built pipeline:</p><pre>ITransformer model = trainingPipeline.Fit(trainingDataView);</pre><h3>3. Evaluate model</h3><p>After the training, we evaluate the model using the training data. The Evaluate function needs a IDataView as parameter which containers all the predictions using the test dataset split, so we apply Transform to the model, and then take the AsDynamic value.</p><pre>// Make bulk predictions and calculate quality metrics<br>ConsoleWriteHeader(&quot;Create Predictions and Evaluate the model quality&quot;);<br>IDataView predictionsDataView = model.Transform(testDataView);<br>           <br>// Show the performance metrics for the multi-class classification            <br>var classificationContext = mlContext.MulticlassClassification;<br>var metrics = classificationContext.Evaluate(predictionsDataView, labelColumnName: LabelAsKey, predictedLabelColumnName: &quot;PredictedLabel&quot;);<br>ConsoleHelper.PrintMultiClassClassificationMetrics(trainer.ToString(), metrics);</pre><p>Finally, we save the model:</p><pre>mlContext.Model.Save(model, predictionsDataView.Schema, outputMlNetModelFilePath);</pre><h4>Run the app to train the model</h4><p>You should proceed as follows in order to train a model your model:</p><ol><li>Set ImageClassification.Train as starting project in Visual Studio</li><li>Press F5 in Visual Studio. The training process will start and will take more or less time depending on how many images you are training with.</li><li>After the training process has finished, in order to update the consumption app with the new trained model, you must copy/paste the generated ML.NET model file (assets/inputs/imageClassifier.zip) and paste it into the consumption app project (assets/inputs/MLNETModel) which simulates and end-user app which is only running the model for making predictions.</li></ol><h3>4. Model consumption code</h3><p>First, you need to load the model created during Model training</p><pre>ITransformer loadedModel = mlContext.Model.Load(modelLocation,out var modelInputSchema);</pre><p>Then, you create a predictor engine, and make a sample prediction:</p><pre>var predictionEngine = mlContext.Model.CreatePredictionEngine&lt;ImageData, ImagePrediction&gt;(loadedModel);</pre><pre>IEnumerable&lt;ImageData&gt; imagesToPredict = LoadImagesFromDirectory(imagesFolder, true);</pre><pre>//Predict the first image in the folder<br>//<br>ImageData imageToPredict = new ImageData<br>{<br>    ImagePath = imagesToPredict.First().ImagePath<br>};</pre><pre>var prediction = predictionEngine.Predict(imageToPredict);</pre><pre>Console.WriteLine(&quot;&quot;);<br>Console.WriteLine($&quot;ImageFile : [{Path.GetFileName(imageToPredict.ImagePath)}], &quot; +<br>                    $&quot;Scores : [{string.Join(&quot;,&quot;, prediction.Score)}], &quot; +<br>                    $&quot;Predicted Label : {prediction.PredictedLabelValue}&quot;);</pre><p>The prediction engine receives as a parameter an object of type ImageData (containing 2 properties: ImagePath and Label). Then returns and object of type ImagePrediction, which holds the PredictedLabel and Score (<em>probability</em> value between 0 and 1) properties.</p><p>Let&#39;s run the application and check how our model works! By the way for this execution, I will not reformat test images, push them to the training pipeline as in their original shapes after that I will restart execution.</p><p>Both of these results seem in the pictures below;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*z2SfowViaHzDrWhFs-mIPA.png" /><figcaption>Result: 1 correct, 3 wrong</figcaption></figure><p>As you see above it&#39;s not working well as expected, I and baby ok, but no way Mr. Parker feels calm here(the scene from the spiderman movie, when his father had a car accident and dying in front of him, yeah should be sad! 🤬)</p><p>And even worse our network believes Biden feels sad here… I think this shouldn’t be how you feel when winning the election and become president of the United States.</p><blockquote>So it&#39;s obvious there is something wrong with our model, I dive into the internet to search principles of ANN and best practices of building a training model and it ended up with the idea that standardizing all images.<br>I already mention how it has done above there is also a link at the end of the article to download the entire source code</blockquote><p>Let&#39;s restart the application, this time images will be going through the processing of resize&amp;grayscale before the prediction</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*a82CJ78OR2LrvwQlXeDJ6w.png" /><figcaption>Result: 3 correct, 1 wrong</figcaption></figure><p>As you see, how <a href="https://www.ijsr.net/archive/v6i3/25031706.pdf">image noise reduction</a> improves the accuracy and prediction as well as performance(it runs almost 4 times faster!) of our network significantly.</p><p>I don’t wanna get this article any longer and we are at a good point to end this.<br>You can download full <a href="https://github.com/y3n3rrr/EmotionAnalysisWithMLNET">source code</a> and try with your own custom images, its almost ready to publish for a prod environment but I strongly recommend a better-trained model if you expect better predictions with more accuracy</p><p>This is what I am thinking about the write a new article coming soon with the training set that I recently found. <a href="https://www.kaggle.com/c/challenges-in-representation-learning-facial-expression-recognition-challenge/data">This sample</a> from Kaggle contains thousands of images ready to use train neural networks. This nice <a href="https://medium.com/@jsflo.dev/training-a-tensorflow-model-to-recognize-emotions-a20c3bcd6468">article</a> covers it as well. You can follow up that python-based work or wait for me to handle this, re-create it within .Net Core by using ML.Net</p><p>Of course, I am open to your ideas, I will be more than happy to know what you expect me to pick a topic for a new incoming article as long as its a playground of .Net Core and React ⚛️. You can drop a comment in the section below</p><p>To be continued…</p><p>See you,<br>Mehmet Yener YILMAZ</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd08aeb9aad7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/emotion-analysis-with-building-an-artificial-neural-network-using-ml-net-powered-by-tensorflow-dd08aeb9aad7">Emotion Analysis with building an Artificial Neural Network using ML.NET powered by Tensorflow</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Uploading Large Files as Chunks Using ReactJS & .Net Core]]></title>
            <link>https://medium.com/swlh/uploadig-large-files-as-chunks-using-reactjs-net-core-2e6e00e13875?source=rss-f86b422cc3a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e6e00e13875</guid>
            <category><![CDATA[file-upload]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[large-file-upload]]></category>
            <dc:creator><![CDATA[Mehmet Yener YILMAZ]]></dc:creator>
            <pubDate>Tue, 29 Sep 2020 00:46:31 GMT</pubDate>
            <atom:updated>2023-11-11T18:19:00.880Z</atom:updated>
            <content:encoded><![CDATA[<h3>Uploading Large Files as Chunks Using ReactJS &amp; .Net Core</h3><p>File upload is one of the most common features of a web app(actually any kind of app) today. For most of the scenarios, this process is simple and straightforward. But what if most don&#39;t involve your situation?</p><p>These can come up with any kind of restrictions;<br><a href="https://graphemica.com/%E2%9A%A0">⚠</a> Amount of size limitation for uploading of internal network of your hosting service provider<br><a href="https://graphemica.com/%E2%9A%A0">⚠</a> Proxy server configurations that clients go through to upload files to your system.<br><a href="https://graphemica.com/%E2%9A%A0">⚠</a> Network distributing rules of the particular web server(like <a href="https://www.nginx.com/resources/glossary/load-balancing/">load balancer</a>)</p><p>Any reason above put you in trouble if you don&#39;t wanna play this game on their rules. Actually besides all of these only limitations of browsers can make you suffer;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*6WyePjfITgkO0YYf_OHDmw.png" /><figcaption>As you can see, different browsers and different versions of browsers support different maximum file sizes.</figcaption></figure><p>Its also not good practice to uploading large files by simple HTTP request <a href="https://stackoverflow.com/questions/1922414/file-upload-limit-in-http">this post</a> will help you understand why its not</p><p>Lets assume you need to upload a movie, 24GB as you see below;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*LxNLWasACd3ojaYUJFJHDg.png" /></figure><p>If you try to upload this file with a classic HTTP request you gonna restricted by browser; They will be like;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z0w_IO8xHI7XCaDZI1XWmQ.jpeg" /></figure><p>In this article, I will demonstrate how to upload a file without limitations of size using React Js and .Net Core Web API Project. So stop talking let&#39;s start coding.</p><p>I will make it as simple as possible to focus on the uploading process;</p><p>1)Create a brand new project with npx tool via code below;</p><blockquote># npx create-react-app file-upload-sample</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*fa9z3vWMS6hWkCy_ighCxA.png" /><figcaption>I’m using VS Code</figcaption></figure><p>2) Remove all files except App.js and index.js your project directory should look like this.</p><p>3) To achieve our goal we gonna need the aid of 4 packages; let&#39;s install them with one blow;</p><blockquote># yarn add axios react-bootstrap bootstrap uuid</blockquote><p>Why do we need them? well, let me make a quick description of it;</p><p>axios; making asynchronous network requests<br>react-bootstrap bootstrap; make our UI looks nice, progress bar particularly<br>uuid; generating unique names(Guid) for each individual files</p><p>4) open index.js file copy &amp; paste import ‘bootstrap/dist/css/bootstrap.min.css’;<br>your file should look like this</p><pre>import React from “react”;<br>import ReactDOM from “react-dom”;<br>import App from “./App”;<br>import “bootstrap/dist/css/bootstrap.min.css”;</pre><pre>ReactDOM.render(<br> &lt;React.StrictMode&gt;<br>  &lt;App /&gt;<br> &lt;/React.StrictMode&gt;,<br> document.getElementById(“root”)<br>);</pre><p>5) Let me say, If you can bear with me follow up each section to understand what&#39;s really doing or simply go to the end of the article to see the end up of App.js file</p><p>First clear the content of the App component and adjust import statements we installed above;</p><pre>import React, { useEffect, useState } from &quot;react&quot;;<br>import { ProgressBar, Jumbotron, Button, Form } from &quot;react-bootstrap&quot;;<br>import { v4 as uuidv4 } from &quot;uuid&quot;;<br>import axios from &quot;axios&quot;;</pre><pre>function App() {<br>  return &lt;&gt;&lt;/&gt;;<br>}</pre><pre>export default App;</pre><p>Go official <a href="https://react-bootstrap.github.io/components/progress/">react-bootstrap</a> site to get a progress-bar component I picked one for u, feel free to update the style of this component for your own app<br>Also, add all required properties that will be used for the uploading process</p><pre>import React, { useEffect, useState } from &quot;react&quot;;<br>import { ProgressBar, Jumbotron, Button, Form } from &quot;react-bootstrap&quot;;<br>import { v4 as uuidv4 } from &quot;uuid&quot;;<br>import axios from &quot;axios&quot;;</pre><pre>function App() {<br>  const [showProgress, setShowProgress] = useState(false)<br>  const [counter, setCounter] = useState(1)<br>  const [fileToBeUpload, setFileToBeUpload] = useState({})<br>  const [beginingOfTheChunk, setBeginingOfTheChunk] = useState(0)<br>  const [endOfTheChunk, setEndOfTheChunk] = useState(chunkSize)<br>  const [progress, setProgress] = useState(0)<br>  const [fileGuid, setFileGuid] = useState(&quot;&quot;)<br>  const [fileSize, setFileSize] = useState(0)<br>  const [chunkCount, setChunkCount] = useState(0)</pre><pre>const progressInstance = &lt;ProgressBar animated now={progress} label={`${progress}%`} /&gt;;</pre><pre>  return &lt;&gt;&lt;/&gt;;<br>}</pre><pre>export default App;</pre><p>Add useEffect hook, This will provide us an iteration of uploading chunks</p><pre>useEffect(() =&gt; {<br>    if (fileSize &gt; 0) {<br>      fileUpload(counter);<br>    }<br>  }, [fileToBeUpload, progress])</pre><p>Add react-bootstrap components to set up UI</p><pre>return (<br>    &lt;Jumbotron&gt;<br>      &lt;Form&gt;<br>        &lt;Form.Group&gt;<br>          &lt;Form.File id=&quot;exampleFormControlFile1&quot; onChange={getFileContext} label=&quot;Example file input&quot; /&gt;<br>        &lt;/Form.Group&gt;<br>        &lt;Form.Group style={{ display: showProgress ? &quot;block&quot; : &quot;none&quot; }}&gt;<br>          {progressInstance}<br>        &lt;/Form.Group&gt;<br>      &lt;/Form&gt;<br>    &lt;/Jumbotron &gt;<br>  );</pre><p>Now we have a file upload element in our web page now we need a callback function to get file details, before that chunk size property which indicates amount of size for each chunk at top of our component;</p><pre>const chunkSize = 1048576 * 3;//its 3MB, increase the number measure in mb</pre><p>now add our callback handler</p><pre>const getFileContext = (e) =&gt; {</pre><pre>resetChunkProperties();<br>const _file = e.target.files[0];<br>setFileSize(_file.size)</pre><pre>const _totalCount = _file.size % chunkSize == 0 ? _file.size / chunkSize : Math.floor(_file.size / chunkSize) + 1; // Total count of chunks will have been upload to finish the file<br>    setChunkCount(_totalCount)</pre><pre>setFileToBeUpload(_file)<br>    const _fileID = uuidv4() + &quot;.&quot; + _file.name.split(&#39;.&#39;).pop();<br>    setFileGuid(_fileID)<br>  }</pre><p>and reset function of component properties</p><pre>const resetChunkProperties = () =&gt; {<br>    setShowProgress(true)<br>    setProgress(0)<br>    setCounter(1)<br>    setBeginingOfTheChunk(0)<br>    setEndOfTheChunk(chunkSize)<br>  }</pre><p>At this point we have the file to be uploaded, the number of chunks it will be split into, also beware we set fileID to ensure the name of the file will be unique in the remote source once it&#39;s done</p><p>Now we need to cut this big file to small pieces will be uploaded and set counter to follow the sequence of the process, the function below works for this;</p><pre>const fileUpload = () =&gt; {<br>    setCounter(counter + 1);<br>    if (counter &lt;= chunkCount) {<br>      var chunk = fileToBeUpload.slice(beginingOfTheChunk, endOfTheChunk);<br>      uploadChunk(chunk)<br>    }<br>  }</pre><p>The definition of the function above;</p><pre>const uploadChunk = async (chunk) =&gt; {<br>    try {<br>      debugger<br>      const response = await axios.post(&quot;<a href="https://localhost:44356/weatherforecast/MultiUpload">https://localhost:44356/weatherforecast/Upload</a>Chunks&quot;, chunk, {<br>        params: {<br>          id: counter,<br>          fileName: fileGuid,<br>        },<br>        headers: { &#39;Content-Type&#39;: &#39;application/json&#39; }<br>      });<br>      debugger<br>      const data = response.data;<br>      if (data.isSuccess) {<br>        setBeginingOfTheChunk(endOfTheChunk);<br>        setEndOfTheChunk(endOfTheChunk + chunkSize);<br>        if (counter == chunkCount) {<br>          console.log(&#39;Process is complete, counter&#39;, counter)<br>          await uploadCompleted();<br>        } else {<br>          var percentage = (counter / chunkCount) * 100;<br>          setProgress(percentage);<br>        }<br>      } else {<br>        console.log(&#39;Error Occurred:&#39;, data.errorMessage)<br>      }</pre><pre>} catch (error) {<br>      debugger<br>      console.log(&#39;error&#39;, error)<br>    }<br>  }</pre><p>Before fading to .Net Core there is one more function we need, it indicates the last one of the chunks has been uploaded and the process is finished</p><pre>const uploadCompleted = async () =&gt; {<br>    var formData = new FormData();<br>    formData.append(&#39;fileName&#39;, fileGuid);</pre><pre>const response = await axios.post(&quot;<a href="https://localhost:44356/weatherforecast/UploadComplete">https://localhost:44356/weatherforecast/UploadComplete</a>&quot;, {}, {<br>      params: {<br>        fileName: fileGuid,<br>      },<br>      data: formData,<br>    });</pre><pre>const data = response.data;<br>    if (data.isSuccess) {<br>      setProgress(100);<br>    }<br>  }</pre><p>If you go through each step properly App.js file should look like this at the end;</p><pre>import React, { useEffect, useState } from &quot;react&quot;;<br>import { ProgressBar, Jumbotron, Button, Form } from &quot;react-bootstrap&quot;;<br>import { v4 as uuidv4 } from &quot;uuid&quot;;<br>import axios from &quot;axios&quot;;</pre><pre>const chunkSize = 1048576 * 3; //its 3MB, increase the number measure in mb</pre><pre>function App() {<br>  const [showProgress, setShowProgress] = useState(false);<br>  const [counter, setCounter] = useState(1);<br>  const [fileToBeUpload, setFileToBeUpload] = useState({});<br>  const [beginingOfTheChunk, setBeginingOfTheChunk] = useState(0);<br>  const [endOfTheChunk, setEndOfTheChunk] = useState(chunkSize);<br>  const [progress, setProgress] = useState(0);<br>  const [fileGuid, setFileGuid] = useState(&quot;&quot;);<br>  const [fileSize, setFileSize] = useState(0);<br>  const [chunkCount, setChunkCount] = useState(0);</pre><pre>const progressInstance = (<br>    &lt;ProgressBar animated now={progress} label={`${progress}%`} /&gt;<br>  );</pre><pre>useEffect(() =&gt; {<br>    if (fileSize &gt; 0) {<br>      setShowProgress(true);<br>      fileUpload(counter);<br>    }<br>  }, [fileToBeUpload, progress]);</pre><pre>const getFileContext = (e) =&gt; {<br>    const _file = e.target.files[0];<br>    setFileSize(_file.size);</pre><pre>const _totalCount =<br>      _file.size % chunkSize == 0<br>        ? _file.size / chunkSize<br>        : Math.floor(_file.size / chunkSize) + 1; // Total count of chunks will have been upload to finish the file<br>    setChunkCount(_totalCount);</pre><pre>setFileToBeUpload(_file);<br>    const _fileID = uuidv4() + &quot;.&quot; + _file.name.split(&quot;.&quot;).pop();<br>    setFileGuid(_fileID);<br>  };</pre><pre>const fileUpload = () =&gt; {<br>    setCounter(counter + 1);<br>    if (counter &lt;= chunkCount) {<br>      var chunk = fileToBeUpload.slice(beginingOfTheChunk, endOfTheChunk);<br>      uploadChunk(chunk);<br>    }<br>  };</pre><pre>const uploadChunk = async (chunk) =&gt; {<br>    try {<br>      const response = await axios.post(<br>        &quot;<a href="https://localhost:44356/weatherforecast/UploadChunks">https://localhost:44356/weatherforecast/UploadChunks</a>&quot;,<br>        chunk,<br>        {<br>          params: {<br>            id: counter,<br>            fileName: fileGuid,<br>          },<br>          headers: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>        }<br>      );<br>      const data = response.data;<br>      if (data.isSuccess) {<br>        setBeginingOfTheChunk(endOfTheChunk);<br>        setEndOfTheChunk(endOfTheChunk + chunkSize);<br>        if (counter == chunkCount) {<br>          console.log(&quot;Process is complete, counter&quot;, counter);<br>          await uploadCompleted();<br>        } else {<br>          var percentage = (counter / chunkCount) * 100;<br>          setProgress(percentage);<br>        }<br>      } else {<br>        console.log(&quot;Error Occurred:&quot;, data.errorMessage);<br>      }<br>    } catch (error) {<br>      console.log(&quot;error&quot;, error);<br>    }<br>  };</pre><pre>const uploadCompleted = async () =&gt; {<br>    var formData = new FormData();<br>    formData.append(&quot;fileName&quot;, fileGuid);</pre><pre>     const response = await axios.post(<br>      &quot;<a href="https://localhost:44356/weatherforecast/UploadComplete">https://localhost:44356/weatherforecast/UploadComplete</a>&quot;,<br>      {},<br>      {<br>        params: {<br>          fileName: fileGuid,<br>        },<br>        data: formData,<br>      }<br>    );</pre><pre>const data = response.data;<br>    if (data.isSuccess) {<br>      setProgress(100);<br>    }<br>  };</pre><pre>return (<br>    &lt;Jumbotron&gt;<br>      &lt;Form&gt;<br>        &lt;Form.Group&gt;<br>          &lt;Form.File<br>            id=&quot;exampleFormControlFile1&quot;<br>            onChange={getFileContext}<br>            label=&quot;Example file input&quot;<br>          /&gt;<br>        &lt;/Form.Group&gt;<br>        &lt;Form.Group style={{ display: showProgress ? &quot;block&quot; : &quot;none&quot; }}&gt;<br>          {progressInstance}<br>        &lt;/Form.Group&gt;<br>      &lt;/Form&gt;<br>    &lt;/Jumbotron&gt;<br>  );<br>}</pre><p>To prevent this article gets longer I will cut the configuration and helper methods usage definition which is accessible source code I&#39;m gonna share at the end of this article</p><p>Create a new web application with an <strong>API </strong>template. I will not even change the name of the initial file, I will put my codes in WeatherForecastController.cs file.</p><p>There are 2 endpoints and 1 static helper method we need to code;</p><p>UploadChunks; Which gathering all pieces of the file and save these each chunk as a file into /Temp` folder.</p><p>UploadComplete; It indicates the latest chunk of the file has been uploaded and now time to merge these chunks to generate the original file.</p><p>MergeChunks; After the upload process is complete it stars to merge each chunk respectively and remove the merged chunk file</p><p>here is the full code;</p><pre>namespace FileUploadSample.Controllers<br>{<br>    public class ResponseContext<br>    {<br>        public dynamic Data { get; set; }<br>        public bool IsSuccess { get; set; } = true;<br>        public string ErrorMessage { get; set; }<br>    }</pre><pre>[ApiController]<br>    [Route(&quot;[controller]&quot;)]<br>    public class WeatherForecastController : ControllerBase<br>    {<br>        private IConfiguration configuration;</pre><pre>private readonly ILogger&lt;WeatherForecastController&gt; _logger;<br>        private readonly ResponseContext _responseData;<br>        public int chunkSize;<br>        private string tempFolder;</pre><pre>public WeatherForecastController(IConfiguration configuration, ILogger&lt;WeatherForecastController&gt; logger)<br>        {<br>            this.configuration = configuration;<br>            _logger = logger;<br>            chunkSize = 1048576 * Convert.ToInt32(configuration[&quot;ChunkSize&quot;]);<br>            tempFolder = configuration[&quot;TargetFolder&quot;];<br>            _responseData = new ResponseContext();<br>        }</pre><pre>[HttpPost(&quot;UploadChunks&quot;)]<br>        public async Task&lt;IActionResult&gt; UploadChunks(string id, string fileName)<br>        {<br>            try<br>            {<br>                var chunkNumber = id;<br>                string newpath = Path.Combine(tempFolder + &quot;/Temp&quot;, fileName + chunkNumber);<br>                using (FileStream fs = System.IO.File.Create(newpath))<br>                {<br>                    byte[] bytes = new byte[chunkSize];<br>                    int bytesRead = 0;<br>                    while ((bytesRead = await Request.Body.ReadAsync(bytes, 0, bytes.Length)) &gt; 0)<br>                    {<br>                        fs.Write(bytes, 0, bytesRead);<br>                    }<br>                }<br>            }<br>            catch (Exception ex)<br>            {<br>                _responseData.ErrorMessage = ex.Message;<br>                _responseData.IsSuccess = false;<br>            }<br>            return Ok(_responseData);<br>        }</pre><pre>[HttpPost(&quot;UploadComplete&quot;)]<br>        public IActionResult UploadComplete(string fileName)<br>        {<br>            try<br>            {<br>                string tempPath = tempFolder + &quot;/Temp&quot;;<br>                string newPath = Path.Combine(tempPath, fileName);<br>                string[] filePaths = Directory.GetFiles(tempPath).Where(p =&gt; p.Contains(fileName)).OrderBy(p =&gt; Int32.Parse(p.Replace(fileName, &quot;$&quot;).Split(&#39;$&#39;)[1])).ToArray();<br>                foreach (string filePath in filePaths)<br>                {<br>                    MergeChunks(newPath, filePath);<br>                }<br>                System.IO.File.Move(Path.Combine(tempPath, fileName), Path.Combine(tempFolder, fileName));<br>            }<br>            catch (Exception ex)<br>            {<br>                _responseData.ErrorMessage = ex.Message;<br>                _responseData.IsSuccess = false;<br>            }<br>            return Ok(_responseData);<br>        }</pre><pre>private static void MergeChunks(string chunk1, string chunk2)<br>        {<br>            FileStream fs1 = null;<br>            FileStream fs2 = null;<br>            try<br>            {<br>                fs1 = System.IO.File.Open(chunk1, FileMode.Append);<br>                fs2 = System.IO.File.Open(chunk2, FileMode.Open);<br>                byte[] fs2Content = new byte[fs2.Length];<br>                fs2.Read(fs2Content, 0, (int)fs2.Length);<br>                fs1.Write(fs2Content, 0, (int)fs2.Length);<br>            }<br>            catch (Exception ex)<br>            {<br>                Console.WriteLine(ex.Message + &quot; : &quot; + ex.StackTrace);<br>            }<br>            finally<br>            {<br>                if (fs1 != null) fs1.Close();<br>                if (fs2 != null) fs2.Close();<br>                System.IO.File.Delete(chunk2);<br>            }<br>        }<br>    }<br>}</pre><p>Its all done now run your react via # yarn statand API project to test our code; once you select the file it will be cut into chunks and pumped to Temp folder.. see quick demonstration video below;</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FiOVwPHyBlYI%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DiOVwPHyBlYI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FiOVwPHyBlYI%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/558a991172b22ad2498eb032ad4763ee/href">https://medium.com/media/558a991172b22ad2498eb032ad4763ee/href</a></iframe><p>As you see in the video above, for each uploaded chunks saved into the Temp folder, after the last chunk uploaded all of the files merged to generate original .mp4 file then removed the files inside of the Temp folder.</p><p>With this approach, you can upload any kind of file having no concerns for the size of the file as well as you have enough space in remote source,<br>Many cloud file transfer platforms like WeTransfer, Google use this approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*Iz1Z-W7-Z6Q2r0VtThyDDA.jpeg" /></figure><p>You can access <a href="https://github.com/y3n3rrr/LargeFileUpload">source code here</a>, hope you find it useful, and if you have any question or need help drop a comment in the section below I will be more than happy to help you.</p><p>Farewell,<br>Mehmet Yener YILMAZ</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e6e00e13875" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/uploadig-large-files-as-chunks-using-reactjs-net-core-2e6e00e13875">Uploading Large Files as Chunks Using ReactJS &amp; .Net Core</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monitoring Metrics of .Net Core Web API project using Prometheus and Grafana]]></title>
            <link>https://medium.com/swlh/monitoring-metrics-of-net-core-web-api-project-using-prometheus-and-grafana-128c802f5bd3?source=rss-f86b422cc3a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/128c802f5bd3</guid>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[grafana]]></category>
            <dc:creator><![CDATA[Mehmet Yener YILMAZ]]></dc:creator>
            <pubDate>Mon, 25 May 2020 15:35:21 GMT</pubDate>
            <atom:updated>2020-05-26T11:59:54.198Z</atom:updated>
            <content:encoded><![CDATA[<h3>Monitoring Metrics of .Net Core Web API project using Prometheus and Grafana</h3><p>Monitoring resources is one of the most useful and major features of an application, especially when its in need of scalability, pick load and suffer from time to time performance issues or just your customer enjoy watching some fancy analysis dashboard that makes him feel happy about pay you money 😄</p><p>Recently I am requested to develop a pretty dashboard within .Net Core Web Application(3.1) that customers can monitor resource usage as well as system performance in detail. <br>As an average middle-aged developer eager to learn I had started to investigate every topic, forums, articles and every possible solution includes GitHub RTR projects. Many of them relating .net core 2.x and various, not stable packages, none of them works this is why I have decided to write this article(Don’t judge me if you already found a working solution, maybe I missed it. Btw why are you here if you have found it? let us discuss it another topic 😄).</p><p>There are many 3rd party tools out there, What I am about to do here is; building a .Net Core Web Application from scratch using 2 of these most widely used open-source software, Prometheus and Grafana.</p><h3>What is Prometheus?</h3><p><a href="https://github.com/prometheus">Prometheus</a> is an open-source system monitoring and alerting toolkit originally built at <a href="https://soundcloud.com/">SoundCloud</a>. Since its inception in 2012, many companies and organizations have adopted Prometheus, and the project has a very active developer and user <a href="https://prometheus.io/community">community</a>. It is now a standalone open source project and maintained independently of any company. To emphasize this, and to clarify the project’s governance structure, Prometheus joined the <a href="https://cncf.io/">Cloud Native Computing Foundation</a> in 2016 as the second hosted project, after <a href="https://kubernetes.io/">Kubernetes</a>. Prometheus is a big topic by itself, to find out more information in detail <a href="https://prometheus.io/docs/introduction/overview/">click here</a></p><h3>What is Grafana?</h3><p>Grafana is an open source visualization and analytics software. It allows you to query, visualize, alert on, and explore your metrics no matter where they are stored. In plain English, it provides you with tools to turn your time-series database (TSDB) data into beautiful graphs and visualizations. If you need more information, you can take a look in <a href="https://grafana.com/grafana/">official web site</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*NY__4gohoI9XadppLXwMWw.png" /></figure><p>Both of these software has much more to talk about and contains huge documentaris in its official web sites, but I want to cut off talking short and dive into coding!</p><p>Lets create new .Net Core Web API project;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0yZlTip-w6LMxnDaM24Utg.png" /></figure><p>you can choose whatever you wish, I have selected “API” as my initial project template to speed up goal, just mind .netcore version of your project. By the time I write this article, the latest version of .Net Core Framework is 3.1, I don’t think there will be a problem for new incoming versions. All you need to do update your pages regarding Prometheus and AppMetric. (But game rules might change again on 4.x 😊, especially for middleware which I’m about to share).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*iFQhSMzZwiZpahNUQyrEcw.png" /><figcaption>I’ve chosen API template for this demo app, you can choose either Web App or MVC. it doesn’t matter</figcaption></figure><p>Now install Prometheus packages via Package Manager Console running commands below;</p><blockquote><em>Install-Package prometheus-net<br>Install-Package prometheus-net.AspNetCore</em></blockquote><p>After install packages add the line below into Startup.cs to to start exposing a default set of metrics. After editing it should look like below;</p><pre>public void ConfigureServices(IServiceCollection services)<br>{</pre><pre>services.AddMetrics();//Add this -&gt; to set default metrics data configuration<br>services.AddControllers();</pre><pre>}</pre><pre>// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.</pre><pre>public void Configure(IApplicationBuilder app, IWebHostEnvironment env)<br>{</pre><pre>if (env.IsDevelopment())<br>{<br>app.UseDeveloperExceptionPage();<br>}</pre><pre>app.UseHttpsRedirection();<br>app.UseRouting();</pre><pre>app.UseHttpMetrics();//Add this line -&gt; this is metric middleware which contains process of gathering metrics</pre><pre>app.UseMetricServer();//Add this line -&gt; I dont know why its needed but pretty sure for good reason :)</pre><pre>app.UseAuthorization();<br>app.UseEndpoints(endpoints =&gt; {<br>endpoints.MapControllers();<br>});<br>}</pre><blockquote>Cautions!: In the Configure method you must add these lines above of <em>app.UseEndPoints(…); </em>or it won&#39;t work</blockquote><p>it means; you will not get any metric data, I have experienced this searching many hours in pain😭. At least I will save yours…</p><p>Mission Complete!, now let&#39;s test it; Run your application and send a get request to https://localhost:44335/metrics the endpoint, If you see a page like this;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*la-5A8k7SyyKRovLW12HiQ.png" /></figure><p>It means well done!, these are default metrics data which has been set as default configuration by Prometheus.</p><p><strong>Customize your metrics data (Optional)</strong></p><p>This stuff makes Prometheus running, but in real life scenario, you probably want to gather some extra or filter metrics specifically so take a step forward to customize our metrics;</p><p>There are some different types of metric data supported by Prometheus and available to report according to their official <a href="https://prometheus.io/docs/concepts/metric_types/">documentation</a>.</p><p>Some of them;<br>Counter; A counter is a cumulative metric that represents a single <a href="https://en.wikipedia.org/wiki/Monotonic_function">monotonically increasing counter</a> whose value can only increase or be reset to zero on restart, so its better usage place when you want to track the total number of requests that your services handle during Req/Resp middleware lifecycle</p><p>Histogram; A histogram samples observations (usual things like request durations or response sizes) and counts them in configurable buckets. It also provides a sum of all observed values. We can use histograms metrics to gather durations of requests handled by services</p><p>We need to implement our own custom middleware to gather these metrics;</p><p>Create a “<em>Middleware</em>” folder and add a new class file; “<em>MetricMiddleware.cs</em>”</p><p>Copy and paste content below;</p><pre>public class MetricMiddleware<br>{</pre><pre>private readonly RequestDelegate _request;</pre><pre>public MetricMiddleware(RequestDelegate request)<br>{<br>_request = request ?? throw new Exception(string.Format(&quot;Context is empty; {0}&quot;, nameof(request)));<br>}</pre><pre>public async Task Invoke(HttpContext context, MetricReporter reporter)<br>{<br>if (context.Request.Path.Value == &quot;/metrics-text&quot;)<br>{<br>await _request.Invoke(context);<br>return;<br>}</pre><pre>var sw = Stopwatch.StartNew();</pre><pre>try<br>{<br>await _request.Invoke(context);<br>}<br>finally<br>{<br>sw.Stop();<br>reporter.RegisterRequest();<br>reporter.RegisterResponseTime(context.Response.StatusCode, context.Request.Method, sw.Elapsed);<br>}<br>}<br>}</pre><p>Now we will create our own metric collector class; create a new class with name of “MetricReporter.cs” and copy-paste the codes below;</p><pre>public class MetricReporter<br>{<br>private readonly ILogger&lt;MetricReporter&gt; _logger;</pre><pre>private readonly Counter _requestCounter;</pre><pre>private readonly Histogram _responseTimeHistogram;</pre><pre>public MetricReporter(ILogger&lt;MetricReporter&gt; logger)</pre><pre>{</pre><pre>_logger = logger ?? throw new ArgumentNullException(nameof(logger));</pre><pre>_requestCounter =</pre><pre>Metrics.CreateCounter(&quot;total_requests&quot;, &quot;The total number of requests serviced by this API.&quot;);</pre><pre>_responseTimeHistogram = Metrics.CreateHistogram(&quot;request_duration_seconds&quot;,</pre><pre>&quot;The duration in seconds between the response to a request.&quot;, new HistogramConfiguration</pre><pre>{</pre><pre>Buckets = Histogram.ExponentialBuckets(0.01, 2, 10),</pre><pre>LabelNames = new[] { &quot;status_code&quot;, &quot;method&quot; }</pre><pre>});</pre><pre>}<br>public void RegisterRequest()<br>{<br>_requestCounter.Inc();<br>}</pre><pre>public void RegisterResponseTime(int statusCode, string method, TimeSpan elapsed)<br>{<br>_responseTimeHistogram.Labels(statusCode.ToString(), method).Observe(elapsed.TotalSeconds);<br>}<br>}</pre><p>Notice Counter and Histogram instances here, are included from the Prometheus library which we installed before. So add “<em>using Prometheus;</em>” and “using Microsoft.Extensions.Logging;” to log these data</p><p>Now open your Startup.cs file and add your custom middleware; your file should look like below after edited;</p><pre>public class Startup<br>{</pre><pre>public Startup(IConfiguration configuration)<br>{<br>Configuration = configuration;<br>}</pre><pre>public IConfiguration Configuration { get; }</pre><pre>// This method gets called by the runtime. Use this method to add services to the container.</pre><pre>//services.Configure&lt;KestrelServerOptions&gt;(options =&gt; { options.AllowSynchronousIO = true; });</pre><pre>public void ConfigureServices(IServiceCollection services)</pre><pre>{</pre><pre>services.AddMetrics();//Add this -&gt; to set default metrics data configuration</pre><pre>services.AddControllers();</pre><pre>}</pre><pre>// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.</pre><pre>public void Configure(IApplicationBuilder app, IWebHostEnvironment env)</pre><pre>{</pre><pre>if (env.IsDevelopment()){<br>app.UseDeveloperExceptionPage();<br>}</pre><pre>app.UseHttpsRedirection();</pre><pre>app.UseRouting();</pre><pre>//app.UseHttpMetrics();//Add this line -&gt; this is metric middleware which contains process of gathering metrics</pre><pre>app.UseMiddleware&lt;MetricMiddleware&gt;();</pre><pre>app.UseMetricServer();//Add this line -&gt; I dont know why its needed but I believe there is good reason :)</pre><pre>app.UseAuthorization();</pre><pre>app.UseEndpoints(endpoints =&gt; {</pre><pre>endpoints.MapControllers();</pre><pre>});<br>}<br>}</pre><p>Finally open Program.cs and copy-paste below;</p><pre>public class Program</pre><pre>{</pre><pre>public static void Main(string[] args)</pre><pre>{</pre><pre>CreateHostBuilder(args).Build().Run();</pre><pre>}</pre><pre>public static IHostBuilder CreateHostBuilder(string[] args) =&gt;</pre><pre>Host.CreateDefaultBuilder(args)</pre><pre>.UseMetricsWebTracking()</pre><pre>.UseMetrics(options =&gt;</pre><pre>{</pre><pre>options.EndpointOptions = endpointOptions =&gt;</pre><pre>{</pre><pre>endpointOptions.MetricsTextEndpointOutputFormatter = new MetricsPrometheusTextOutputFormatter();</pre><pre>endpointOptions.MetricsEndpointOutputFormatter = new MetricsPrometheusProtobufOutputFormatter();</pre><pre>endpointOptions.EnvironmentInfoEndpointEnabled = false;</pre><pre>};</pre><pre>})</pre><pre>.ConfigureWebHostDefaults(webBuilder =&gt; {<br>webBuilder.UseStartup&lt;Startup&gt;();<br>});<br>}</pre><p>This is configuration settings of how our application metrics data formatted, we have set output formatter with MetricsPrometheusTextOutputFormatter to make Prometheus server able to get data peacefully</p><p>Our business with the application is done! Now open your browser go and download the latest version of the <a href="https://prometheus.io/download/">Prometheus server</a> that matches your operating system.</p><p>Unzip and open “<em>prometheus.yml</em>” file;<br>I will not explain all properties in detail since it already contains a brief description as comments if you want further information you can access it <a href="https://prometheus.io/docs/prometheus/latest/configuration/configuration/">here</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*iuy0t3lYANOvgxpp0ddEPA.png" /></figure><p>Quick Tips; If you didn’t select SSL configuration while creating your.Net Core Web application remove “scheme: https” since its set to https as default behind the scene;<br>Add your applications running port number as targets as well as metrics_path of job which indicates Prometheus service communicate with our app to gather metrics,</p><p>Note; Now I think you see why we have used ‘/metrics-text’ endpoint in our custom metric-middleware 😊</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bKrJ9f3uVf1NA4GrwIKvaQ.png" /></figure><p>Now close and save prometheus.yml file and double click “prometheus.exe”. You should see something like the pic on the left. Beware your web application is running and configuration settings are correct in your web application and Prometheus server otherwise it will be stuck at “Server is ready to receive web requests” message.</p><p>It means Prometheus server up and running in foreground now and last setup we need to make is; yes Grafana!</p><p>Now open go and download latest version of <a href="https://grafana.com/grafana/download">Grafana Server</a> that matches your operating system.</p><p>And now... <br>The most epic challenge of your development career has come!<br>…<br>Unzip the file and double click “grafana-server.exe”, that&#39;s all. 🤣</p><p>To access Grafana open browser and make a request to <a href="http://localhost:3000/">http://localhost:3000</a>, then you will see the login page of Grafana UI</p><p>Username: admin<br>Password: admin</p><p>These are initial credentials of Grafana after you log in the system it will ask you to change, feel free to change as you wish</p><p>After log in to grafana, click ‘Add your first data source’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LHmTMck2Xaa9_g3MnvLs3w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uxu6pHHEtYADBdMGa-vs_g.png" /></figure><p>As you have seen here Grafana has ability to communicate with plenty of data source technologies, we will choose Prometheus as our data source.</p><p>Incoming form, type : “http://localhost:9090” which is endpoint of running prometheus server in our machine. Leave default rest and scroll down click “Save &amp; Test” then you should see some notification toaster message that says process completed successfully</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PJRt_zB9HXPvNPOlTEPKGQ.png" /><figcaption>If grafana service isn&#39;t able to access the endpoint you provide, you will see an error message within red background notification</figcaption></figure><p>Now we need to create a dashboard template to demonstrate our metrics data with delightful analytical UI elements. <br>There is more than one way to do this in Grafana, you can create your own custom dashboard template or you can even buy ready to use a template which composed for very specific purposes.</p><p>Again to speed up the process and make it easy we gonna use a ready-to-use free dashboard template provided by the Grafana team to help us young tech kiddies like me. <br>All we need the unique ID of the template; I already know its “2204”</p><p><strong>Now follow these steps to create your first Grafana template;</strong></p><p>▹ Now go to “<em>Create -&gt; Import</em>” via navbar to create your first dashboard.</p><p>▹Type <em>2204 </em>and click “<em>Load</em>”</p><p>▹ Then to the following settings type your name of the dashboard</p><p>▹ Select “<em>General</em>” as Folder and select your Prometheus data source which <br> you created before then click “<em>Import</em>”</p><p>And here is the awesome magic of Grafana;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ePX9-rnXOpkbi8-OlLbwNg.png" /><figcaption>Remember these are free Grafana dashboard, some charts might be unnecessary</figcaption></figure><p>Its real time analysis dashboard, want to see some action? <br>Go to your running .net application and make some requests to provide more metrics data to Grafana</p><p>I am using Postman to make request to web application, it doesn’t matter you can do this in browser as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I4JG1RSQE8Jtj13xn5nqJA.png" /></figure><p>After making some dummy requests you will see Grafana reacts it in a few seconds</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zZ1Vv1ybrF63h8tARQMcGQ.png" /></figure><p>As you see above, rpm(“request per minute”) increased respectively.</p><p>Grafana also shows the environment info about our application; Environment, application, data source. <br>Summarize; this value indicates which period your dashboard updates</p><p>That’s all I am willing to share about integrating .net core web application with Prometheus and Grafana. Actually as you see we only integrate our app with Prometheus and Grafana totally independent from this communication it only gets data from Prometheus to draw dashboard.</p><p>I hope it helps and goes to aid of people who seek furter assistance.</p><p>I share the <a href="https://github.com/y3n3rrr/WeathercastDemoApp">source code</a> of this demo application in my Github repo.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=128c802f5bd3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/monitoring-metrics-of-net-core-web-api-project-using-prometheus-and-grafana-128c802f5bd3">Monitoring Metrics of .Net Core Web API project using Prometheus and Grafana</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Push Notification with Firebase in React Native Application]]></title>
            <link>https://medium.com/swlh/push-notification-with-firebase-in-react-native-application-9306aaac746d?source=rss-f86b422cc3a9------2</link>
            <guid isPermaLink="false">https://medium.com/p/9306aaac746d</guid>
            <category><![CDATA[push-notification]]></category>
            <category><![CDATA[react-native-development]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Mehmet Yener YILMAZ]]></dc:creator>
            <pubDate>Tue, 26 Nov 2019 01:19:01 GMT</pubDate>
            <atom:updated>2019-12-08T11:26:53.177Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Push Notifications with Firebase in React Native</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2hXY_XdMCw6UNU5yBCmF5w.png" /></figure><p>Firebase is a mobile and web application development platform developed by Firebase, Inc. in 2011, then acquired by Google in 2014. As of October 2018, It has 18 products, which used by 1.5 million apps. What we are about to do here is using Push Notification technology within a React Native App and increment this number by +1 🤣</p><p>This article assumes you have required packages installed on your device and ready to build React Native application. But anyone out of this assumption can follow these official <a href="https://facebook.github.io/react-native/docs/getting-started">instructions</a>, I don’t mention all steps in detail here.</p><p>Create your project:</p><blockquote>npx react-native init PushNotificationSample</blockquote><p>Thats it! <br>Run it, use it or sell it whatever … I’m done here, goodbye.</p><p><em>just kidding..</em></p><p>a short sight of my package.json file to indicate versions of the packages;</p><p>{<br>&quot;name&quot;: &quot;PushNotificationSample&quot;,<br>…<br> “dependencies”: {<br>“react”: “16.9.0”,<br>“react-native”: “0.61.5”,<br>“react-native-firebase”: “⁵.5.6”<br>},</p><p>Now we begin to settle Firebase environment;<br>Go to <a href="https://console.firebase.google.com/">https://console.firebase.google.com/</a><br>Log in and create a project; Click Add project on the page below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v1YNtCa4eENLU2gFUON1Zw.png" /></figure><p>Enter your project name as you wish and click Continueand click Continueagain and in next page select Default Firebase Account</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*9AOB7o7L9gxv-VBO784BEg.png" /></figure><p>then click Create project</p><p>After some creating process, you will be welcomed by this page</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x10scmnIU4PTuDslCMrcCA.png" /></figure><p>My project’s name is “Push Notification Sample”<br>Now click the Androidicon to create an application</p><ol><li>Register app<br> <em>Android package name; <br>Copy your project name from \android\app\src\main\AndroidManifest.xml</em> file.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xzSPWzT-LzJ_bhn_zUnQuQ.png" /><figcaption>its how your AndroidManifest.xml should look like at the end. Now Just get the project name. (highlighted)</figcaption></figure><p>Then click “Register app”<br>2) Click “Download the google-services.json” file and move this file to \android\app directory, then click “Next”<br>3) Click “Next”<br>4) Click “Skip this step”. Yeah, these last two are my favourites as well.</p><p>Now flip back to your project and install this package;</p><blockquote>npm install — save react-native-firebase</blockquote><p>and run this to link packages to your application</p><blockquote>react-native link react-native-firebase</blockquote><p>Note:I am using VS Code but you can use any text editor except Excel<br>Open <em>\android\build.gradle</em> in your editor and copy+paste<br>classpath com.google.gms:google-services:4.2.0 to dependencies section.</p><p>It should look like this;<br>dependencies {<br> classpath(“com.android.tools.build:gradle:3.4.2”)<br> classpath com.google.gms:google-services:4.2.0 //NEW LINE!!<br> // NOTE: Do not place your application dependencies here; they belong<br> // in the individual module build.gradle files<br>}</p><p>Then open <em>android\app\build.gradle</em> file and copy&amp;paste apply plugin: ‘com.google.gms.google-services’ to very bottom.<br>It should look like this;<br>…<br>apply from: file(“../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle”); applyNativeModulesAppBuildGradle(project)<br>apply plugin: ‘com.google.gms.google-services’<br>Also before leave this file copy firebase dependencies;<br>dependencies {<br>implementation project(‘:react-native-firebase’)<br>implementation fileTree(dir: “libs”, include: [“*.jar”])<br>implementation “com.facebook.react:react-native:+”<br> // Firebase dependencies (Copy&amp;paste these two lines)<br>add this line if you wish to use badge on Android<br>implementation &quot;com.google.android.gms:play-services-base:16.1.0&quot;<br>implementation &quot;com.google.firebase:firebase-core:16.0.9&quot;<br>implementation &quot;com.google.firebase:firebase-messaging:18.0.0&quot;<br>implementation &#39;me.leolin:ShortcutBadger:1.1.21@aar&#39; // &lt;-- its optional<br>...</p><p>Note: in official Firebase documentation(https://rnfirebase.io) it says;</p><p>“In <em>android/gradle/wrapper/gradle-wrapper.properties</em>, update the gradle URL to gradle-4.4-all.zip”</p><p><strong>But its wrong</strong>! At the moment I post this article RN gradle version in <em>\android\gradle\wrapper\gradle-wrapper.properties</em> file gradle-5.5 and<br>RN Minumum supported Gradle version is 5.2 so its gonna make you encounter a compile error if you change it to gradle-4.4-all.zip.</p><p><strong>Solution:</strong> Don&#39;t touch, leave it as it is.</p><p>In <em>android/build.gradle</em> check that you have google() specified in the buildScript repositories section<br>buildscript {<br> repositories {<br> google() // ← Check this line exists and is above jcenter<br> jcenter()<br> // …<br> }<br> // …<br>}</p><p>Open <em>\android\app\src\main\java\com\pushnotificationsample\MainApplication.java</em> file add these two import statements;<br>import io.invertase.firebase.messaging.RNFirebaseMessagingPackage;<br>import<br>io.invertase.firebase.notifications.RNFirebaseNotificationsPackage;</p><p>and edit getPackages() method. It should look like this;<br>@Override<br>protected List&lt;ReactPackage&gt; getPackages() {<br>@SuppressWarnings(“UnnecessaryLocalVariable”)<br>List&lt;ReactPackage&gt; packages = new PackageList(this).getPackages();<br>// Packages that cannot be autolinked yet can be added manually here, for example:<br>// packages.add(new MyReactNativePackage());<br>packages.add(new RNFirebaseMessagingPackage()); // ← Add this line<br>packages.add(new RNFirebaseNotificationsPackage()); // ← Add this line<br>return packages;<br>}</p><p>Open <em>\android\app\src\main\AndroidManifest.xml</em>file and copy-paste some XML inside application element, just above &lt;/application&gt; tag<br>and your file should look like this;</p><p>&lt;manifest xmlns:android=”http://schemas.android.com/apk/res/android&quot; package=”com.pushnotificationsample”&gt;<br>...<br>&lt;activity<br>android:name=”com.facebook.react.devsupport.DevSettingsActivity” /&gt;<br>&lt;! — Copy Begin →<br>&lt;service android:name=”io.invertase.firebase.messaging.RNFirebaseMessagingService”&gt;&lt;intent-filter&gt;<br>&lt;action android:name=”com.google.firebase.MESSAGING_EVENT” /&gt;<br>&lt;/intent-filter&gt;<br>&lt;/service&gt;&lt;meta-data<br>android:name=”com.google.firebase.messaging.default_notification_icon” android:resource=”@drawable/ic_launcher” /&gt;<br>&lt;meta-data android:name=”com.google.firebase.messaging.default_notification_color” android:resource=”@color/notificationColor” /&gt;<br>&lt;meta-data android:name=”com.google.firebase.messaging.default_notification_channel_id” android:value=”@string/default_notification_channel_id”/&gt;<br>&lt;receiver android:name=”io.invertase.firebase.notifications.RNFirebaseNotificationReceiver”/&gt;<br>&lt;receiver android:enabled=”true” android:exported=”true” android:name=”io.invertase.firebase.notifications.RNFirebaseNotificationsRebootReceiver”&gt;&lt;intent-filter&gt;<br>&lt;action android:name=”android.intent.action.BOOT_COMPLETED”/&gt;<br>&lt;action android:name=”android.intent.action.QUICKBOOT_POWERON”/&gt;<br>&lt;action android:name=”com.htc.intent.action.QUICKBOOT_POWERON”/&gt;<br>&lt;category android:name=”android.intent.category.DEFAULT” /&gt;<br>&lt;/intent-filter&gt;&lt;/receiver&gt;<br>&lt;! — Copy End →<br>&lt;/application&gt;<br>&lt;/manifest&gt;</p><p>And under project root directory create a file named bgMessaging.js and edit index.js</p><p>bgMessaging.js file should look like this;<br>// @flow<br>import firebase from ‘react-native-firebase’;<br>import type from ‘react-native-firebase’;<br>export default async (message) =&gt; {<br>return Promise.resolve();<br>}</p><p>index.js file should look like this;<br>import {AppRegistry} from ‘react-native’;<br>import App from ‘./App’;<br>import {name as appName} from ‘./app.json’;<br>AppRegistry.registerComponent(appName, () =&gt; App);<br>AppRegistry.registerHeadlessTask(‘RNFirebaseBackgroundMessage’, () =&gt;<br>bgMessaging); // ← Add this line</p><p>Under <em>\android\app\src\main\res </em>directory create a folder drawable<br>and put an icon file which will have been use as notification icon.<br>You can download it by <a href="https://www.dropbox.com/s/r52dpi318ti6eda/ic_launcher.png?dl=0">here</a>. Create another folder raw and put your notification ring tone <a href="https://www.dropbox.com/s/1bv8293or4xat3a/sampleaudio.mp3?dl=0">sound file</a> here. <br>Open <em>\android\app\src\main\res\values directory create a file named color.xml and copy-paste the content below;<br></em>&lt;resources&gt;<br>&lt;color name=”notificationColor”&gt;#FFA500&lt;/color&gt;<br>&lt;/resources&gt;</p><p><em>And in same directory open strings.xml file make it look like this;<br></em>&lt;resources&gt;<br> &lt;string name=”app_name”&gt;PushNotificationSample&lt;/string&gt;<br> &lt;string name=”default_notification_channel_id” translatable=”false”&gt;fcm_pushnotification_default_channel&lt;/string&gt;<br>&lt;/resources&gt;</p><p>Thats it! Now run the app;</p><blockquote>react-native run-android</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*UaSl0w8sVgoCXnhFjHJKsw.png" /></figure><p>and open Grow -&gt; Cloud Messaging click <em>Notifications </em>tab and click New notification, you gonna generate your notification in this form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/1*tsu4eCchlEwNNBKWww3Lug.jpeg" /></figure><p>if everything is ok, you should see something like this on your device.</p><p>Best advantage of this approach you can save the identity all of the clients(tokens) you want and choose who you want to send notification in future its very easy and usefull.</p><p>This is how you send notification to your clients in Firebase.</p><p>Lets use another application named <em>pushtry.</em> Its a third party web application. Open <a href="https://pushtry.com/">https://pushtry.com/</a> which used for sending test notification.</p><p>You don&#39;t need Firebase or any other platform that you need to log in for sending a notification, its just a simple web app with anonymous access. You were able to send GCM test notification, I said “w<em>ere” </em>because it&#39;s deprecated and moving to FCM as well, this is why its losing popularity among developers so using Firebase seems the best way to send a notification. But lets respect olds and show the way. <em>😢</em></p><p>Copy your server key and token and edit the message detail to be sent<br>You can get your server key from firebase account as you see below;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kcs3gTgmaGaB5o0_S1CV-Q.png" /></figure><p>You can get your token from console, open debug in your app and it would be prompted in console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Y3l8XbJyi3xlQ10vA8AIA.png" /></figure><p>Also you can edit notification form data as you see below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*KmSkefwtwm3P34gf5dqssg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*PUGqt0Fu_MC4oRiapeZXOQ.jpeg" /></figure><p>Before send notification, push home button or whatever it routes to main screen.</p><p>Your app suppose to work in Background, now click “Send”. If everything goes okay, you should see something like this on your device.</p><p>You will be able to send notification even your app is not running on the foreground so you can keep your clients up to date and share information regarding your business.</p><p>I have also shared the source codes and there are comments and description in detail that may assist you to understand what&#39;s going on here, just check my repo link below.</p><p>You can download full <a href="https://github.com/y3n3rrr/PushNotificationSample">source code here.</a> There is another tutorial coming soon about an application in .Net Core which I use as application layer. It will send notifications to Firebase and eventually, you will see notifications on your device just like the pics above.</p><p>Please feel free to comment in the section below also let me know if you have any questions about this tutorial I will be happy to assist you. Also, don&#39;t hesitate to share your ideas if you think it fits better with our needs here.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9306aaac746d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/push-notification-with-firebase-in-react-native-application-9306aaac746d">Push Notification with Firebase in React Native Application</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>