Introduction: A sitemap is a crucial element in optimizing your website for search engines. It serves as a roadmap, guiding search engine crawlers through the various pages and content on your site. In this blog post, we'll delve into what sitemaps are, how they are used, and provide step-by-step guidance on creating one. Additionally, we'll explore an alternative method using online sitemap generators. What is a Sitemap? A sitemap is essentially a file that provides information about the structure and content of your website to search engines. It lists URLs and includes additional metadata such as the last modification date, change frequency, and priority of each page. The primary purpose is to help search engine bots crawl and index your site more efficiently. How is a Sitemap Used? 1. Improved Crawling: Search engines use sitemaps to discover and understand the organization of your website. This aids in more efficient crawling, ensuring that no important pages are missed. 2. Enhanced Indexing: By providing metadata like the last modification date and change frequency, sitemaps help search engines prioritize and index pages based on their relevance and importance. 3. SEO Benefits: Having a well-structured sitemap can positively impact your site's search engine optimization (SEO), potentially leading to better visibility in search results. How to Create a Sitemap: 1. Understand Your Website Structure: Before creating a sitemap, familiarize yourself with your site's structure, including main pages, categories, and any dynamic content. 2. Choose a Sitemap Generation Method: Manual Method: Use a text editor to create an XML file, including URLs, last modification dates, etc. CMS Plugin: If you use a content management system (CMS) like WordPress, leverage plugins such as Yoast SEO or Google XML Sitemaps. Online Sitemap Generator: Use online tools like XML-sitemaps.com or Screaming Frog to automatically generate a sitemap. 3. Include Relevant Information: For each URL, include the `<loc>` (URL), `<lastmod>` (last modification date), `<changefreq>` (change frequency), and `<priority>` (priority) tags. 4. Save and Upload: Save the XML file with a ".xml" extension (e.g., "sitemap.xml"). Upload it to your website's root directory using FTP or your hosting provider's file manager. 5. Submit to Search Engines: Submit your sitemap to search engines using their webmaster tools (e.g., Google Search Console, Bing Webmaster Tools). Alternative Method: Using Online Sitemap Generator: 1. Choose a Tool: Select an online sitemap generator such as XML-sitemaps.com or Screaming Frog. 2. Enter Your Website URL: Input your website's URL into the generator. 3. Generate and Download: Click the "Generate" or "Crawl" button to initiate the process. Once complete, download the generated sitemap file. 4. Upload and Submit: Upload the downloaded file to your website's root directory and submit it to search engines. Conclusion: Creating and submitting a sitemap is a fundamental step in optimizing your website for search engines. Whether you opt for manual creation or use online generators, a well-structured sitemap can significantly contribute to better search engine visibility and improved SEO. Regularly update and submit your sitemap to ensure that search engines stay informed about changes to your site's content.
Scenario: If someone say you Hey, can you transfer one of MySQL data to another MySQL data and we think about SSIS or other Thing if yes then these article made for you to reduce your effort and save your time Introduction: In the dynamic landscape of database management, the need to seamlessly access and integrate data from multiple sources has become paramount. Whether it's consolidating information from disparate servers or synchronizing databases for backup and redundancy, MySQL offers a robust solution through its querying capabilities. In this guide, we delve into the art of fetching data from one MySQL server to another using SQL queries. This method, often overlooked in favor of complex data transfer mechanisms, provides a streamlined approach to data migration, enabling developers and database administrators to efficiently manage their resources. Through a combination of MySQL's versatile querying language and the innovative use of the FEDERATED storage engine, we'll explore how to establish connections between servers, replicate table structures, and effortlessly transfer data across the network. From setting up the environment to executing queries and troubleshooting common challenges, this tutorial equips you with the knowledge and tools to navigate the intricacies of cross-server data retrieval with ease. As we know We gonna use FEDERATED feature of MySQL workbench so first we need to check that our workbench support FEDERATED engine or not? Simply open workbench and run below code show engines; It shows all engines and check our system support FEDERATED OR NOT If your system also not support don't worry we gonna enable it Open your folder where you save MySQL serve file In my case it in my C drive C>ProgramData>MySQL>MySQL Server 8.0>my.ini open it in notepad++ or preferable software Insert FEDERATED key word in script like below Now need to restart MySQL Press Window+R button and paste services.msc press ok> find MySQL and restart it Now go to workbence and run show engines; code Now your FEDERATED engine get supported It show like below Now our system Support FEDERATED engine This same process need to apply on destination side because both server (from source to destination server) need to support FEDERATED engine Now we make sure to we have permission of access source server for that we need to make user and and give permission of database and tables Below code demonstrate to make user and give permission to user CREATE USER 'hmysql'@'192.168.1.173' IDENTIFIED BY 'Hardik...'; GRANT ALL PRIVILEGES ON *.* TO 'hmysql'@'192.168.1.173' WITH GRANT OPTION; FLUSH PRIVILEGES; Now make connection of that user(we make above on source side) on destination server(our system) Click on plus(+) icon as shown in image and fill all detail Below image is for detail of user connection After filling details our user added like below image Go to user(hardikmysql) and find from which table we want to take data using MySQL query Here i am taking 'actor' table from 'sakila' database which look like below Now we need to run FEDERATED query on our system(destination server) with url string Our MySQL query like below CREATE TABLE `actor` ( `actor_id` smallint unsigned NOT NULL AUTO_INCREMENT, `first_name` varchar(45) NOT NULL, `last_name` varchar(45) NOT NULL, `last_update` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`actor_id`), KEY `idx_actor_last_name` (`last_name`) ) ENGINE=FEDERATED default charset=utf8mb4 CONNECTION='mysql://hmysql:Hardik...@192.168.1.173:3306/sakila/actor'; Here main part is below ENGINE=FEDERATED default charset=utf8mb4 CONNECTION='mysql://hmysql:Hardik...@192.168.1.173:3306/sakila/actor'; Here 'mysql' is mandatory for connection string you can not use other word. 'hmysql' is user name 'Hardik...' is password for user '192.168.1.173' is server adderess '3306' is port number 'sakila' is database name 'actor' is table name Now run above table code and you get data in our system(destination server)
Introduction: Welcome to our guide on normalizing JSON files using Power Query! JSON (JavaScript Object Notation) has become one of the most popular formats for storing and exchanging data due to its simplicity and flexibility. However, working with JSON data in its raw form can sometimes be challenging, especially when dealing with nested structures or arrays. In this blog post, we'll delve into the process of normalizing JSON files using Power Query. Normalization refers to the process of organizing data into a tabular format, making it easier to analyze and manipulate. First we need to import data in power bi desktop with Json connection. click on get data inside home tab of power BI Desktop. Click on more tab to get Json file connection. click on connect button which redirect you to your systeam then choose your Json file. You redirect to your Power Query Editor. Power Query editor interface like below. Here we can check Table.column ,Table.Rows are in form of list Not in form of row data that we want. Click on one of list which show what inside of list. Here data inside of one list. It has around 121 rows inside one list and we need to expand it Row wise. so first idea is to exoand list column by left click on right side of column and choose expand new rows for every column which contains list. But you notice that for one row there are multiple sub-rows which is not appropriate like below. Here for extract time(First row) only one row valid other rows are not valid or duplicate so these happen with every rows and roes count for table is not acceptable. so our approach is not valid here we miss something In above image(image 5) table.rows and table.column has list in row. if you turn by turn expand both list you notice that both list has data(in some case same rows and in other case rows are not same) with same row count which indicate that both lists data are connected with each other. so we need to make a new column which combine both list in form of table . Go to add column tab> select custome column it open custome column interface and write code like below. Table.FromColumns({[Tables.Columns],[Tables.Rows]}) it add new column in existing table like below. when you click on customecolumns row you will redirect to expanded version of table which look like below. now we can normalize data. now we can separate table to multiple table by for easy for data modeling create duplicate table and filter out as needed now close your power query tab and you get your desired output below is advance editor code if you don't want to apply all steps that we implemented above let Source = Json.Document(File.Contents("C:\Users\MagnusMinds\Downloads\Order_CRHESTHASH_ET_FD2024-03-11_PID184_ORD686_MRK2024-03-08 09 14 44.410_T00638455040948575166.json")), #"Converted to Table" = Table.FromRecords({Source}), #"Expanded Tables" = Table.ExpandListColumn(#"Converted to Table", "Tables"), #"Expanded Tables1" = Table.ExpandRecordColumn(#"Expanded Tables", "Tables", {"Name", "QueryStartTimeUtc", "QueryEndTimeUtc", "QueryElapsedTimeMs", "CurrentRow", "Columns", "Rows", "OriginalRowCount", "Hashes", "MasterRecordIsDuplicate"}, {"Tables.Name", "Tables.QueryStartTimeUtc", "Tables.QueryEndTimeUtc", "Tables.QueryElapsedTimeMs", "Tables.CurrentRow", "Tables.Columns", "Tables.Rows", "Tables.OriginalRowCount", "Tables.Hashes", "Tables.MasterRecordIsDuplicate"}), #"Changed Type" = Table.TransformColumnTypes(#"Expanded Tables1",{{"Tables.Name", type text}, {"Tables.QueryStartTimeUtc", type datetime}, {"Tables.QueryEndTimeUtc", type datetime}, {"Tables.QueryElapsedTimeMs", Int64.Type}, {"Tables.CurrentRow", Int64.Type}, {"Tables.Columns", type any}, {"Tables.Rows", type any}, {"Tables.OriginalRowCount", Int64.Type}, {"Tables.Hashes", type any}, {"Tables.MasterRecordIsDuplicate", type logical}}), #"Expanded Tables.Rows" = Table.ExpandListColumn(#"Changed Type", "Tables.Rows"), #"Added Custom" = Table.AddColumn(#"Expanded Tables.Rows", "Customcolumn", each Table.FromColumns({[Tables.Columns],[Tables.Rows]})), #"Expanded Customcolumn" = Table.ExpandTableColumn(#"Added Custom", "Customcolumn", {"Column1", "Column2"}, {"Customcolumn.Column1", "Customcolumn.Column2"}), #"Expanded Customcolumn.Column1" = Table.ExpandRecordColumn(#"Expanded Customcolumn", "Customcolumn.Column1", {"Name"}, {"Customcolumn.Column1.Name"}) in #"Expanded Customcolumn.Column1"
Introduction Have you ever tried to add holidays which lie between today (or any dates) to a specific date or the same kind of scenario? If yeah Then this article helps you Scenario Recently, I faced a situation where I needed to add days to the current date (today) which depends on the total number of hours left for a particular employee. Means employee A has 150 hours left and spent only 6-hour for one working day, then divide the hour by daily spend and find the date (forecast date) where employee A completed their task but did not include holidays and weekends. Let’s consider employee X. Get 15 fore-cast days on the basis of the hours left. Those 15 days do not include weekends and holidays, which we need to add to the current date (today). Let’s consider Employee X got 3 days of weekend or public holiday out of 15 days, then it also needs to add in fore-cast days, which means now 15 days become 18 days. If employee X's forecast date falls on a weekend or a holiday, it is also not applicable. We take some data for solving scenario Holiday Table Logic behind solving this problem is we going to take a separate date table which will help for deriving fore-cast date and add new column of Holidays. After that we add a new column which give us a flag of 0 if Date in weekends or in holidays and 1 for date in working day after that we give rank according to flag with exclude of Flag 0. We make a new date Table which particular Use for Fore-cast Date Using Below DAX Code Here I am taking only 2024 Date field fore-cast Datetable = ADDCOLUMNS( CALENDAR( TODAY(), DATE(2024,12,31) ), "weekday", WEEKDAY([Date],2), "Dayname", FORMAT([Date],"dddd") ) Join holiday Table and fore-cast Date table using Date field Make a new column (Holiday) in Fore-cast Date table which help us to bring only holiday date from holiday table to existing table holiday = RELATED('Holiday Table'[holiday date]) Make another new column with some condition using Dax code which give Flag 0 for those date which are weekends and holidays and 1 for Working days. workingday = IF( NOT('fore-cast Datetable'[weekday]) in {6,7}, IF( 'fore-cast Datetable'[holiday]<>BLANK(), 0, 1 ), 0 ) Add column Which Give day no from Today with ignoring Weekends and holidays Day Number = RANKX( FILTER( ALL('fore-cast Datetable'[Date],'fore-cast Datetable'[workingday]), 'fore-cast Datetable'[workingday]<>0 ), 'fore-cast Datetable'[Date],,ASC ) Our main goal is taking Days on behalf of Hours and find those date which is equivalent to left days from today with ignoring weekends and holidays. Day Number column give us that ability Fore-cast date table Look like below Now make a new column in employee table Forecast date column = var a =FLOOR((Employee[Hour left]/6),1) return MAXX( FILTER( ALL('fore-cast Datetable'[Date],'fore-cast Datetable'[Day Number]), 'fore-cast Datetable'[Day Number]=a ), 'fore-cast Datetable'[Date] ) We can make measure with little bit changes fore-cast date using measure = var a = FLOOR(SUM(employee[hour left])/6,1) return MAXX( FILTER( ALL('fore-cast Datetable'[Date],'fore-cast Datetable'[Day Number]), 'fore-cast Datetable'[Day Number]=a ), 'fore-cast Datetable'[Date] ) Make a table visual If you don’t want to add new table to your Existing data model We can also achieve Without fore-cast date table by creating it on fly. Use below Dax code for column fore-cast date without table refrence = var a = FLOOR(('Employee'[Hour left]/6),1) var b =NETWORKDAYS(TODAY(),TODAY()+a,1) var c = ADDCOLUMNS( CALENDAR(TODAY(),TODAY()+a+b), "weekday", WEEKDAY([Date],2), "dayname",FORMAT([Date],"dddd"), "publikholiday",LOOKUPVALUE('Holiday Table'[Holiday Date],[holiday date],[Date]), "holidaycondition", var a1 = IF( not(WEEKDAY([Date],2)) in {6,7}, IF( LOOKUPVALUE('Holiday Table'[Holiday Date],[holiday date],[Date])<>BLANK(), 0, 1 ), 0 ) RETURN a1 ) var f = ADDCOLUMNS(c,"rank",RANKX(FILTER(c,[holidaycondition]<>0),[Date],,ASC)) var e= MINX(FILTER(f,[rank]=a),[Date]) return e here little bit changes in above code for measure Use below code for measure fore-cast date measurewithout table refrence = var a = FLOOR(sum(employee[hour left])/6,1) var b =NETWORKDAYS(TODAY(),TODAY()+a,1) var c =ADDCOLUMNS( CALENDAR(TODAY(),TODAY()+a+b), "weekday",WEEKDAY([Date],2), "dayname",FORMAT([Date],"dddd"), "publikholiday",LOOKUPVALUE('Holiday Table'[Holiday Date],'Holiday Table'[holiday date],[Date]), "holidaycondition", var a1 = IF( not(WEEKDAY([Date],2)) in {6,7}, IF( LOOKUPVALUE('Holiday Table'[Holiday Date],'Holiday Table'[holiday date],[Date])<>BLANK(), 0, 1 ), 0 ) RETURN a1 ) var f = ADDCOLUMNS(c,"rank",RANKX(FILTER(c,[holidaycondition]<>0),[Date],,ASC)) var e= MINX(FILTER(f,[rank]=a),[Date]) return e Output without Using Table refrence
Introduction to Power BI and Year-to-Date(YTD) & Year-over-Year(YoY) Calculations Power BI is a data visualization and business intelligence tool that allows users to connect to different data sources, transform data, and create insightful reports and dashboards. With Power BI, users can easily perform complex calculations such as YTD calculation, which provides a way to view data from the beginning of the year up to a given point in time. YoY growth is a change in a metric compared to the same period one year prior. There are several approaches to achieve YTD & YoY calculation using DAX in Power BI. Let's use one of the approach to accomplish that. What is Year-to-Date(YTD)? Imagine you’re in February, looking back at all the data from the beginning of the year (January 1st) until today. That’s YTD. It’s like a running total of your performance throughout the current year. How to Calculate Year-toDate(YTD)? Assume we have a calendar & sales table and having a column for sales amount. Now use DAX to develop a measure that computes the current year's YTD revenue. Previous Year-to-Date(PYTD): Now, rewind to the same day in the previous year. The data from January 1st of that year up to that day is PYTD. It’s your benchmark, a reference point to compare your current year’s progress. How to Calculate Previous Year-to-Date(PYTD)? Using SAMEPERIODLASTYEAR function we can get the same date of previous year. Year-over-Year(YoY) Growth: This is where things get exciting! YoY is the change between your current YTD and the PYTD for the same day. It tells you how much you’ve grown (or shrunk) compared to the same period last year. How to calculate YoY growth : Subtract PYTD(YTD Rev LY) from YTD Revenue(YTD Rev) : The DAX functions I utilized to get these calculations : LASTDATE(Dates) : Returns last non blank date STARTOFYEAR(Dates) : Returns the start of year SAMEPERIODLASTYEAR(Dates) : Returns a set of dates in the current selection from the previous year CALCULATE (Expression,Filter,Filter, …) : Evaluates an expression in a context modified by filters. DATESBETWEEN(Dates,StartDate,EndDate) : Returns the dates between two given dates. Conclusion : Calculating YTD and YOY growth in Power BI using DAX is a valuable technique for analyzing financial performance and identifying trends. Furthermore, it's important to note that this comprehensive approach leverages only pre-defined DAX functions. By understanding and practicing these versatile functions, you can unlock the ability to perform a wide range of complex calculations within Power BI, ultimately transforming your data into actionable insights.
In today's data-driven world, efficient storage and management of data are paramount for businesses of all sizes. Nowadays there are multiple data sources available in the market and the need for analytics is vastly increased, hence having a reliable and scalable database management is essential. Amazon Web Services (AWS) offers a robust set of tools for data storage, including the Simple Storage Service (S3), a highly durable and scalable object storage solution, and a fully managed extract, transform, and load (ETL) service known as AWS Glue Script. In this blog, we'll discuss about process of storing and archiving data using an AWS S3 bucket and an AWS Glue script. We'll explore the benefits of this approach and provide a step-by-step guide to help you set up your data storage and archiving solution. Setting Up Data Storage and Archiving with AWS S3 and AWS Glue: Let’s learn how to create S3 Bucket & AWS Glue Script. Step 1) Create an AWS S3 Bucket: Create an S3 bucket in the AWS Management Console. Choose a unique bucket name, Remember to select the appropriate Region & Access settings according to your requirements and configure the necessary permissions. This bucket will be used to store the archived data. Step 2) Configure Life-cycle Policies: Once the bucket is created, We can manage the Life-cycle & Replication Policies of the stored object. Open the created bucket & go to the management tab. Configure the rules for Life-cycle & Replication Policies as per the requirement. We can define rules to transition objects to different storage classes or delete them after a certain period. Step 3) Develop an AWS Glue Script: Now we have created a storage system to store the archived data. The next step is to develop an AWS Glue script to perform the necessary ETL operations on your data. This may include extracting data from various sources, transforming it into the desired format, and loading it into your S3 bucket. AWS Glue supports Python as the scripting language for defining ETL jobs, making it flexible and easy to use for developers and data engineers. Here's a detailed breakdown of how to develop an AWS Glue script: Create a Glue Job: In the AWS Glue console, navigate to the "Jobs" section and click on "Add job". Provide a name for your job and select the IAM role that grants necessary permissions for Glue to access your data sources and write to the S3 bucket. AWS also provides a visual interface that allows users to create, run, and monitor data integration jobs in AWS Glue. It offers a graphical, no-code interface for building AWS Glue jobs with easy steps. Define Data Sources & Destination: Identify the data sources you'll be working with. These can include various types of data repositories such as relational databases, data lakes, or even streaming data sources like Amazon Kinesis. AWS Glue supports a wide range of data sources, allowing you to extract data from diverse platforms. We just have to configure the Source, Transformation if needed & the Destination with the proper connection string. For example, For the Relational Database source, we have to provide a JDBC connection of the server OR Data catalog table. Once the connection is successful we can enter the schema & object name & get the data preview in AWS. After successfully configuring the source & destination location, AWS will automatically generate the ETL script which we can refer to in the script tab. Write Glue Script: In the script editor, We can also directly write the Python code that defines our ETL operations. Let's understand it with an example. We will connect the SQL server Database & execute the SP which will transfer the data into a table. From this table we will archive the data into our S3 bucket. Please find the structure of it below : import sys from awsglue.transforms import * from awsglue.utils import getResolvedOptions from pyspark.context import SparkContext from awsglue.context import GlueContext from awsglue.job import Job args = getResolvedOptions(sys.argv, ["JOB_NAME"]) sc = SparkContext() glueContext = GlueContext(sc) spark = glueContext.spark_session job = Job(glueContext) job.init(args["JOB_NAME"], args) from py4j.java_gateway import java_import source_jdbc_conf = glueContext.extract_jdbc_conf('ConnectionName') java_import(sc._gateway.jvm,"java.sql.Connection") java_import(sc._gateway.jvm,"java.sql.DatabaseMetaData") java_import(sc._gateway.jvm,"java.sql.DriverManager") java_import(sc._gateway.jvm,"java.sql.SQLException") conn = sc._gateway.jvm.DriverManager.getConnection(source_jdbc_conf.get('url') + ";databaseName=DB_NAME", source_jdbc_conf.get('user'), source_jdbc_conf.get('password')) cstmt = conn.prepareCall("{call dbo.sptoGetthedatandtransferintotable(?)}"); results = cstmt.execute(); # Script generated for node SQL Server table SQLServertable_node1 = glueContext.create_dynamic_frame.from_options( connection_type="sqlserver", connection_options={ "useConnectionProperties": "true", "dbtable": "Data_Table", "connectionName": "Connection_name" }, transformation_ctx="SQLServertable_node1", ) # Script generated for node S3 bucket S3bucket_node3 = glueContext.write_dynamic_frame.from_options( frame=SQLServertable_node1, connection_type="s3", format="glueparquet", connection_options={"path": "s3://s3_newcreatedbucket//"}, format_options={"compression": "snappy"}, transformation_ctx="S3bucket_node3", ) conn.close(); job.commit(); Step 4) Version Control: AWS also provides version controling of the job script through GIT so we can track and manage changes. Step 5) Run the Glue Job: Once you're satisfied with the script's functionality, you can run the Glue job either on-demand or schedule it to run at specific intervals. AWS Glue will execute the script, extract data from the defined sources, perform transformations, and load the transformed data into the specified S3 bucket. Step 6) Monitor Job Execution: Monitor the job execution in the AWS Glue console or via AWS Cloud Watch. You can track metrics such as job run time, success/failure status, and resource utilization to ensure that your ETL processes are running smoothly. After following these steps, You should be able to efficiently store/archive data in S3 Bucket using AWS Glue script. Before wrapping up let's understand what are the benefits of AWS S3 & AWS Glue Script Service. Benefits of Using AWS S3 and AWS Glue: Scalability: AWS S3 provides virtually unlimited storage capacity, Individual objects can be up to 5TB in size. Allowing you to scale your storage resources seamlessly as your data grows. Durability: S3 offers 99.999999999% durability for stored objects, this means that if you store 100 billion objects in S3, you will lose one object at most. This ensures that your data is highly resilient and protected against loss. Cost-effectiveness: With AWS S3, you only pay for the storage you use, making it a cost-effective solution for businesses of all sizes. Simplified Management: AWS Glue automates the process of data discovery, transformation, and loading, streamlining the data management process and reducing the need for manual intervention. Integration: Both AWS S3 and AWS Glue seamlessly integrate with other AWS services, such as Amazon RDS, Amazon Redshift, Amazon Athena, and Amazon EMR, allowing you to build comprehensive data pipelines and analytics workflows. Availability: Amazon S3 replicates data across multiple disks, so even if one of them fails, customers can still access their data with no downtime. It Ensures that your data is always available whenever we require it. So Overall to summarize this blog we learned that, by leveraging AWS S3 and AWS Glue, you can build a robust data storage and archiving solution that is scalable, durable, and cost-effective. Whether you're dealing with large volumes of data or need to automate the process of archiving historical data, AWS provides the tools and services you need to streamline your data management workflows. Start exploring the possibilities today and unlock the full potential of your data with AWS. Thank you for your visit. Hoping this blog was helpful & you got what you were looking for. Best of Luck
Establishing your account on Firebase and connecting it with your React APP encompasses multiple steps, such as initiating a Firebase project, adjusting your project settings, and acquiring your Firebase configuration details. Below is a comprehensive, step-by-step guide: Step 1: Go to the Firebase Console From this link, you can go to the Firebase console app https://console.firebase.google.com/ Step 2: Sign in or create a Google Account If you have a Google account you can directly sign in and if you don’t have then you need to create one to sign in Step 3: Create a new Firebase Project Click on the Create a Project button. Enter a Project name. And Click on the Continue button. Enable Google Analytics (Optional) From here you can enable or disable the Google Analytics option. It is recommended to enable Google Analytics for better insights. Once you click on the Continue button, firebase will set your project and redirect you to the Project dashboard. Add an app to your project: Click on the Project Settings button and from there you can see the configuration of your project. Choose the platform for your app (iOS, Android, or Web). Enter an app nickname (optional) and click on Register app. Obtain Firebase configuration details. For a web app, Firebase will provide you with a configuration object containing keys like apiKey, authDomain, projectId, etc. Copy this information as you'll need it in your application. Step 4: Create database For Creating the database, go to the build option and click on the “FireStore Database” option Once you navigate to Firestore Database, click on “Create database” button. Step 5: Install the Firebase Package After creating your React app, change directory to your project's root folder and install the Firebase package by running: npm install firebase Step 6: Initialize Firebase in your React APP Create a new folder inside your project src directory. You can call this firebase_setup. Next, create a firebase.js file inside that folder. Then paste the code generated earlier into this file. Thus, you can fine-tune the generated code as follows: import { initializeApp } from "firebase/app"; import { getFirestore } from "@firebase/firestore" const firebaseConfig = { apiKey: process.env.REACT_APP_apiKey, authDomain: process.env.REACT_APP_authDomain, projectId: process.env.REACT_APP_projectId, storageBucket: process.env.REACT_APP_storageBucket, messagingSenderId: process.env.REACT_APP_messagingSenderId, appId: process.env.REACT_APP_appId, measurementId: process.env.REACT_APP_measurementId }; const app = initializeApp(firebaseConfig); export const firestore = getFirestore(app) Step 7: Test Your Firebase Connection You can test the connection by submitting dummy data to Firestore. Start by creating a handles folder inside your project's src directory. Create a submit handler inside this file. You can call this handlesubmit.js, for instance: import { doc, setDoc } from "@firebase/firestore" import { firestore } from "../firebase_setup/firebase" const handleSubmit = async(testdata) => { const handleSubmit = async(employeeData) => { try { const employeeDocRef = doc(firestore, 'EmployeeDb', 'Employee_tbl'); await setDoc(employeeDocRef, employeeData); console.log("Added employee data successfully"); } catch(e) { console.error("Error adding data employee", e); } } export default handleSubmit //Then inside App.js: import './App.css'; import handleSubmit from "./handler/handlesubmit.js"; import { useState} from 'react'; function App() { const [employee, setEmployee] = useState({ name: "", age: "", position: "", }); // Function to handle input changes const handleChange = (e) => { const { name, value } = e.target; setEmployee({ ...employee, [name]: value }); }; const submithandler = (e) => { e.preventDefault(); handleSubmit(employee); }; return ( <> <div className="form-container" onSubmit={submithandler}> <form action="#" > <div className="form-group"> <label >Employee Data:</label> <input type="text" name="name" placeholder="Name" value={employee.name} onChange={handleChange} /> <input type="text" name="age" placeholder="Age" value={employee.age} onChange={handleChange} /> <input type="text" name="position" placeholder="Position" value={employee.position} onChange={handleChange} /> <input type="submit" value="Submit" /> </div> </form> </div> </> ); } export default App; Run your React app and try submitting data via the form. Refresh the Firebase database console to see the submitted information in your collection. When you run your React app it will look like this. Here when you add all the details of the employee and click on the Submit button Whatever you entered in the form it will be reflected in your Firestore database. Fantastic! You have effectively established your Firebase account and configured it in your react application.
Introduction: In the realm of modern APIs, the provision of clear and comprehensive documentation plays a pivotal role in facilitating developer adoption and ensuring efficient utilization. Swagger, aligned with the OpenAPI Initiative, stands out as a prominent solution, offering machine-readable documentation and a user-friendly interactive interface. In this guide, we'll delve into the seamless integration of Swagger into your .NET Core API. Step 1: Install the necessary packages Add Swashbuckle.AspNetCore NuGet package to a project: dotnet add package Swashbuckle.AspNetCore Add Swashbuckle.AspNetCore.SwaggerUI NuGet package to a project: dotnet add package Swashbuckle.AspNetCore.SwaggerUI Step 2: Add services in program.cs In the program.cs file, include the following service additions: builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); Additionally, add middleware in program.cs to enable Swagger in the development environment: if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } Step 3: Run the API project and access the Swagger UI at: https://your-api-base-url/swagger Ensure the API project is running, and navigate to the provided URL to explore and interact with the Swagger UI seamlessly. Step 3: Execute the APIs and test.
What is Authentication? Authentication is the process of validating the identity of a user or system attempting to access a protected resource. In C# programming, authentication is commonly implemented in various scenarios, including web applications, desktop applications, and services. Types of Authentications Basic Authentication Password-based Authentication Multi-Factor Authentication Token-based Authentication Let’s understand authentication with example. Here I am taking one example of MFA (Two-factor authentication). Step 1: Create the MVC Web Application Open Visual Studio and select File >> New >> Project. After selecting the project, a “New Project” dialog will open. Select ASP.NET Core web app (Model-View-Controller) and press Next and enter project name and click Next. Choose 'Individual Account' as the authentication type and click 'Create' to generate the project. Step 2: Adding QR Codes to configure two-factor authentication We will be using a QR code to configure and sync the Google authenticator app with our web app. Download the qrcode.js JavaScript library from https://davidshimjs.github.io/qrcodejs/ and put it into the “wwwroot\lib” folder in your application. Now, your “wwwroot” folder will have the following structure. Now, Add new scaffolded item in your project by right click on Area folder and select New scaffolded Item under Add section. Select Identity section on left sidebar and click on Add. Now, Select the identity files that you have to add to your project but select file “Account/Manage/EnableAuthenticator” is compulsory for 2FA. Select the DbContext Class of your project and click on add. Open the “Views\Manage\EnableAuthenticator.cshtml” file. You will find @section Scripts at the end of the file. Put the following code in it. @section Scripts { @await Html.PartialAsync("_ValidationScriptsPartial") <script src="~/lib/qrcode/qrcode.js"></script> <script type="text/javascript"> new QRCode(document.getElementById("qrCode"), { text: "@Html.Raw(Model.AuthenticatorUri)", width: 200, height: 200 }); </script> } Note: Change your script path as per your folder structure. This “EnableAuthenticator.cshtml” file already has a div with the id “qrCode” (see the code snippet below). We are generating a QR code inside that div using the qrcode.js library. We are also defining the dimensions of the QR code in terms of width and height. So finally, your “EnableAuthenticator.cshtml” file will look like this. @page @model EnableAuthenticatorModel @{ ViewData["Title"] = "Configure authenticator app"; ViewData["ActivePage"] = ManageNavPages.TwoFactorAuthentication; } <partial name="_StatusMessage" for="StatusMessage" /> <h3>@ViewData["Title"]</h3> <div> <p>To use an authenticator app go through the following steps:</p> <ol class="list"> <li> <p> Download a two-factor authenticator app like Microsoft Authenticator for <a href="https://go.microsoft.com/fwlink/?Linkid=825072">Android</a> and <a href="https://go.microsoft.com/fwlink/?Linkid=825073">iOS</a> or Google Authenticator for <a href="https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2&hl=en">Android</a> and <a href="https://itunes.apple.com/us/app/google-authenticator/id388497605?mt=8">iOS</a>. </p> </li> <li> <p>Scan the QR Code or enter this key <kbd>@Model.SharedKey</kbd> into your two factor authenticator app. Spaces and casing do not matter.</p> <div class="alert alert-info">Learn how to <a href="https://go.microsoft.com/fwlink/?Linkid=852423">enable QR code generation</a>.</div> <div id="qrCode"></div> <div id="qrCodeData" data-url="@Model.AuthenticatorUri"></div> </li> <li> <p> Once you have scanned the QR code or input the key above, your two factor authentication app will provide you with a unique code. Enter the code in the confirmation box below. </p> <div class="row"> <div class="col-md-6"> <form id="send-code" method="post"> <div class="form-floating mb-3"> <input asp-for="Input.Code" class="form-control" autocomplete="off" placeholder="Please enter the code."/> <label asp-for="Input.Code" class="control-label form-label">Verification Code</label> <span asp-validation-for="Input.Code" class="text-danger"></span> </div> <button type="submit" class="w-100 btn btn-lg btn-primary">Verify</button> <div asp-validation-summary="ModelOnly" class="text-danger" role="alert"></div> </form> </div> </div> </li> </ol> </div> @section Scripts { @await Html.PartialAsync("_ValidationScriptsPartial") <script src="~/lib/qrcode/qrcode.js"></script> <script type="text/javascript"> new QRCode(document.getElementById("qrCode"), { text: "@Html.Raw(Model.AuthenticatorUri)", width: 200, height: 200 }); </script> } When we execute the program, a QR code will be generated in this View. Then you can set up two factor authentication using the Google authenticator with the help of this QR code. Step 3: Configure two-factor authentication Before running the application, we need to apply migrations to our app. Navigate to Tools >> NuGet Package Manager >> Package Manager Console. It will open the Package Manager Console. Put in the “Update-Database” command and hit Enter. This will update the database using Entity Framework Code First Migrations. Run the application and click on “Register” in the top right corner of the homepage. You can see a user registration page. Fill in the details and click on the “Register” button as shown in the image below. Upon successful registration, you will be logged into the application and navigated to the home page. Here, you can see your registered Email id at the top right corner of the page. Click on it to navigate to the “Manage your account” page. Select “TwoFactorAuthentication” from the left menu. You will see a page similar to that shown below. Click on the “Set up authenticator app” button. You can see a QR code generated on your screen — it is asking for a “Verification Code”, also as shown in the image below. You need to install the Google Authenticator/Microsoft Authenticator app on your smartphone. It will allow you to scan this QR code in order to generate a Verification Code and complete a two-factor authentication setup. Open Microsoft Authenticator and click on verified IDs at the bottom. Click on “Scan a barcode” and scan the QR code generated by the web app. This will add a new account to Microsoft authenticator and generate a six-digit pin on your mobile screen. This is our two-factor authentication code. This is a TOTP ( time-based one-time password). You can observe that it keeps on changing frequently (life span of 30 seconds). Put this pin in the Verification Code textbox and click on verify. Upon successful verification, you will see a screen similar to the one shown below. This will give you the recovery codes for your account that will help to recover your account in case you are locked out. Take a note of these codes and keep them somewhere safe. Logout of the application and click on login again. Enter your registered email id and password and click on login. Now you can see a the two-factor authentication screen asking for the Authenticator code. Put in the code that is generated in your Google Authenticator app and click on Login. You will be successfully logged into the application and navigated to the home page.