omarokasha1 / TheFirstProject

This is a Learning Management System Solutions Developed from Scratch inside Orange Digital Center Labs By ODC-Flutter WorkForce.
https://www.orangedigitalcenters.com/country/EG/home
10 stars 7 forks source link

Summary of All documentation #22

Open youssefelgebaly opened 2 years ago

youssefelgebaly commented 2 years ago

N|Solid

what is git and github?

Before using GIT we need to understand some Definitions :

image

this is all stages

Important Notes:

  • create repo for every project.
  • create a new branch for every feature or enhancement .
  • no need to connect to remote when working.
  • anyone can push and pull depend on permissions. Note: There are two ways to communicate with your repository with HTTP or SSH I find that ssh is the famous one so I decided to use it . As there are communication that going to happen between two devices so we need to set up the communication between them and make it authorized .So we need to generate a RSA code that the protocol that ssh use for Communicating
ssh-keygen -t rsa -b 4096 -C "your_email@example.com" 

Enter a file in which to save the key (/home/you/.ssh/id_rsa): [Press enter]

Enter passphrase (empty for no passphrase): [Type a passphrase]
Enter same passphrase again: [Type passphrase again]

so to add the code to our ssh protocol on our Ubuntu

ssh-add ~/.ssh/id_rsa

to Get a copy from the RSA code to add to my gitlab server side We need to install

sudo apt-get install xclip

to take a copy to your clipboard

xclip -sel clip < ~/.ssh/id_rsa.pub

Commands Usually Used in Git

1. Git clone

Git clone makes an identical copy of the latest version of a project in a repository and saves it to your computer.

 <command line in git>   git clone <https://name-of-the-repository-link>

2. Git branch

By using branches, several developers are able to work in parallel on the same project simultaneously.

<command line in git>  git branch <branch-name>
      This command will create a branch locally. To push the new branch into the remote repository, you need to use the following command:

      git push -u <remote> <branch-name>
a-Viewing branches: <command> git branch
b-Deleting a branch: <command> git branch -d <branch-name>

3. Git checkout

 To work in a branch, first you need to switch to it. We use git checkout mostly for switching from one branch to another.
<command line in git>   git checkout <name-of-your-branch>

4. Git status

The Git status command gives us all the necessary information about the current branch.
<command line in git>   git status

5. Git add

We need to use the git add command to include the changes of a file(s) into our next commit.
<command line in git>   git add .

6. Git commit

Git commit is like setting a checkpoint in the development process which you can go back to later if needed.(Move files from stage to repo in a local )
<command line in git>   git commit -m "commit message"

7. Git push

After committing your changes, the next thing you want to do is send your changes to the remote server. Git push uploads your commits to the remote repository.
<command line in git>   git push <remote> <branch-name>

8. Git pull

The git pull command is used to get updates from the remote repo. git pull

9. Git merge

The git pull command is used to get updates from the remote repo. git pull

First you should switch to the dev branch:
<command line in git>  git checkout dev

Before merging, you should update your local dev branch:
<command line in git> git fetch

Finally, you can merge your feature branch into dev:
git merge <branch-name>

source Link "https://www.freecodecamp.org/news/10-important-git-commands-that-every-developer-should-know/"

How to restore old versions ?

cd ~/git/your-repo-root git log

find the commit id you want

git checkout .

IMPORTANT NOTE: the trailing . in the previous line is important!

git commit -m "Restoring old source code"

How to Compare files ?

Using  <command line in git> (git diff ) without any arguments: will compare each modified files in your file system against the files in the current checked-out branch (or) tag.

Using  <command line in git> (git diff <tag(or)branch name>):  will compare each modified files in your file system against the files in the specified branch (or) tag without using checked-out branch (or) tag.

Using <command line in git> (git diff <path/to/file_name (or) path/to/folder>): will compare the specified file or files in the folder in your file system against the current checked-out branch (or) tag.

Using  <command line in git> (git diff <tag1(or)branch1 name> <tag2(or)branch2 name>:  will compare all modified files between two branches / tags.

source Link "https://stackoverflow.com/questions/10988757/git-compare-files-before-commit"

How to merge with Master ?

1. //pull the latest changes of current development branch if any
<command line in git>  git pull (current development branch)

2. //switch to master branch
<command line in git>  git checkout master

3. //pull all the changes if any
<command line in git>  git pull

4. //Now merge development into master
 <command line in git> git merge development

5. //push the master branch
<command line in git>  git push origin master

What is the Normal Process to start working on a new Feature ?

create a new branch git branch

steps

pull requests

Pull requests let you tell others about changes you've pushed to a branch in a repository on GitHub. Once a pull request is opened, you can discuss and review the potential changes with collaborators and add follow-up commits before your changes are merged into the base branch.

Steps

First how work git in Android Studio

image ![image](https://user-images.githubusercontent.com/61950354/1# GitHub Actions Automate, customize, and execute your software development workflows right in your repository with GitHub Actions. You can discover, create, and share actions to perform any job you'd like, and combine actions in a completely customized workflow.

Video Link "https://www.youtube.com/watch?v=cP0I9w2coGU&t=161s"53848368-69f6e0af-4a00-44e1-af5e-7a4e00a3f4a0.png)

image

if you do not have git in your pc

and go to Github

image

create an account , enter your data and select your account

image

go to your account in github and click on repositories

image

create a new repository

image

enter your name of repo

image

clicked in create repository

image

and open terminal on your project in android studio Or cmd (cd your project path ) and add this lines line by line

image finally you upload your project in github .

Next How to work in each Branch ?

image

and create a new file if you want

image image

if you want merge this branch in master

First of All We need to add (ssh Key) in your PC

Second Things : Start to Clone Project

git clone git@github.com:omarokasha1/TheFirstProject.git

Third Thing : Start to Make Your Branch and Add Your files

cat .ssh/id_rsa.pub
eval $(ssh-agent -s)
ssh-add ~/.ssh/id_rsa

N|Solid

Testing

What is testing ?

the execution of software and trying all its functions and properties in different ways and to examine all the possibilities that user may carry out while executing the software.

What are objectives we do testing?

  1. It satisfies specified requirements: study the software functionality in detail to find where the bugs are likely to occur.
  2. finding defects: ensure that each line of code it tested.
  3. Preventing defects : finding bugs as early as possible.
  4. Gaining confidence about the level of quality.
  5. Help meeting specific standers.
  6. providing information for decision makers. Create test cases in such a way that testing is done and make they get fixed. Causes of Software Defects Testing vs. Quality Assurance

Software Testing Myths?

  1. Second class career : respected discipline in software development.
  2. Verification of running program :it includes (testing requirements documentation, code inspection static analysis.)
  3. Manual testing only : using testing tools ,performance test tools, testing management tool.
  4. Boring routine test: Demanding creative task testing scenario design .
  5. Testers must make sure that 100% of software work find and error: There will always be a missing bugs.
  6. A tester effectiveness is reflected in the number of bugs found before the software is released to user: No connection >between user happiness and buts testers fount in software, the main concern for theme is only a working software. Developing vs. Testing

We have a Bug but what is the Bug?

Is The deviation of the actual result from the expected result.`

A person makes an Error That produce a Fault or a Bug in the program code. that might causes a failure in the software.

Software Requirement Specification

Is detailed description (purpose, overall description, system feature, interface requirements) the main reference for Expected result

If there is no SRS:

  1. Standards.
  2. Communication.
  3. Statistics.
  4. Life Experience In software testing there is not only a Software Bugs but there is also a Specification Bugs .

Test Inputs

Bug Addressing

What is it? Bug reporting >> Fixing bug >>Recheck it is bug free and there is no bug introduced. How? on Bug Tracking System.

Test Suite: is Test cases of the same module by Test Procedure which is Test Execution all Test Steps if: pass AR==ER fail AR!=ER block no possibility to test

Test Case Documentation:

  1. Unique id.
  2. Bugs Priority: from P1 to P4.
  3. Description.
  4. Additional info.
  5. Revision History.
  6. Test procedure.
  7. ER :expected result.
  8. Revision History :Created (date/name) Modified(date/name)

maintainability of test case :

we need the simplicity and easy of changing a test case.

  1. Do not include steps for obvious easy to guess scenarios.
  2. Take repeat scenarios put those into an external document put a reference of this external document in test cases.
  3. Do not build steps on an information in may be changed or deleted.

Avoid those test case practices:

  1. Dependency between test cases.
  2. poor description of test case.

4 levels of Testing - comparison

Reasons for Test Cases

  1. Happy scenario Test To pass.
  2. Bad scenario Test To fail.

Test Design Techniques

why? To design the suitable test cases for each type and part of software, Write the right number of test cases to cover all code possibilities and write minimum number effective number of test cases . types:

Black Box Testing Techniques. == 'Specification based testing'

Applies foe functional and non-functional testing, without reference to the internal structure of the system. with: mainly applicable to higher levels of testing (System Testing and Acceptance Testing). types:

White Box Testing Techniques. =='Glass box Testing or Structure base Testing'

Testing based on an analysis of the internal structure of the component or system. with: mainly applicable to lower levels of testing (Unit Testing or integration testing).

Statement test cases for a segment of code will always =< of Branch / Decision test cases. Branch/decision testing is a more complete form of testing than statement testing.

Why is Testing imporant? What is Testing?

Testing Principles

  1. Early Testing.
  2. Absence-of-errors fallacy.
  3. Testing shows presence of defects.
  4. Testing is context dependent.
  5. Defect clustering(80%20%).
  6. Pesticide paradox.
  7. Exhaustive testing is impossible(risk analysis and priorities). res

Fundamental Test Process

  1. Test planning and control
    • Test Planning: Specification of test objectives(i.e. find defects as much as we can, Give information to decision making, ...)._
    • Control: (Ongoing activity )keep monitoring all the test activities as long as you work on project.
    • Comparing the plan with actual progress, if not Reporting then taking action.
  2. Test analysis and design
    • Test analysis: Test basis(Requirements, Software integrity level, Risk analysis reports ,Structure of software, interface specification) the Test condition
    • Design: Test cases then prioritizing, identifying test data, prioritizing, test environment setup. output: traceability matrix
  3. Test implementation and execution
    • Implementation: create Test suites and implementing test pressures and create Test Data and Test harnesses(stubs and drivers). verify test environment setup
    • Execution Logging or recording Test Log file : (compare if Discrepancies AR != ER, tester name ,date ,AR, ER,TR), then retesting then the Regression testing
  4. Evaluating exit criteria and reporting
    • Exit criteria: to determine when to stop(i.e. Test execution coverage ,fault found, cost or time).
    • Reporting: write test summary report for all stakeholders to know the stage we have reached.
  5. Test closure activities
    • at each milestone(i.e. SW is released, Test project is completed or canceled, )
    • check: planned deliverables.
    • close: reports.
    • Document: system acceptance..
    • Finalizing Archiving: Handover Test ware(i.e. Test harness, tools ,test cases, procedures, test suites, data) to Maintenance organization_

Fundamental Test process

psychology of testing code of Ethics

Testing throughout software life cycle SDLC models:

1. Sequential model.

2. Iterative model. dividing the SDLC to mini SDLC with regression testing

3. Incremental model. _Sequential and alterative

Verification Testing and validation Testing

Verification: Requirements. Validation: propose customer needs

Testing types

1. Functional Testing (Black Box)

2. Non-Functional Test How the System works? SW characteristics

1. Performance
2. load
3. stress
4. Usability
5. Maintainability 
6. Reliability
7. portability

3. Structure testing (white Box) with all Testing levels specially unit testing and integrated testing

4. Testing Related to Change types:

  1. Confirmation testing(retesting) : After fix bugs.
  2. Regression Testing

5. Maintenance-Testing

with all testing types and testing level why

Impact Analysis

determine the the extent of effect on system and how much regression testing to do.

Static Techniques

Dynamic Testing

code execution high coast and long time

SRSD

SD, Use cases, UML diagram

SW Testing life cycle STLC

  1. Requirement Analysis.

    1. meeting with (Business Analyst, Architecture, Client, Technical Manager, Any Stakeholders)
    2. choose the Testing Types (Functional ,security, performance)
    3. Testing focus with my priorates
  2. Test Planning. Test plan Document.

    • Objective &scope of the project.
    • Testing types.
    • Testing effort estimation and resource planning.
    • Selection of testing tool if required.
    • Test schedules.
    • Roles and responsibilities.
    • Test deliverable.
    • Entry & Exit criteria.
    • Risks.
    • In scope &out of scope.
  3. Test Case Development.

    • Create test cases for each module/function.
    • Preparing test data.
    • Requirements traceability matrix documentation if changed we do impact analysis.
  4. Environment setup.

  5. Test Execution.

    1. Smoke Testing(validation Testing)
    2. Start Test execution according to the test plan.
    3. Define the status of each test case according to SRS(passed or failed or not applicable).
    4. Report a bug through (Bug or Defect Tracking Tool like Jira, Mantis)
    5. Status Report and send the report to developer.(Count of the founded bugs, Bugs Priorities, Bug Severity)
    6. Start executing with new build ( Fixed bugs to close it, New functionalities.)
    7. Confirmation Test
  1. Test Cycle Closure.
    1. make acceptance testing and deliver UAT( user acceptance Testing) Document
    2. write project Bugs report contains all the bugs found in this project(Fixed Bugs/Known issues).

Test case writing

Test case definition : _IEEE: Documentation of specified inputs or predicted result, A group of activates which have expected results and actual results happen in a certain sequence in order to check the specification and advantage of the product.

The sources of Test Cases:

  1. SRS document (use cases, user story ).
    • _Detailed description of a software system to be developed with its functional and non functional requirements.
      1. Functional requirement.
      2. non-fictional requirement.
      3. may include Use cases. _

Test Case Format

Test case attributes :

  1. Test case ID. Unique identifier

    • Naming Convention
    • TC+ Project Name+ Function name +TC number
  2. Test case Title/Description. short description of test case & should be effective to convey the test case

  3. Test case Summary. Detailed description of test case & additional information needed for the test case to execute.

  4. Pre-condition/Assumption. any pre-requisite required to excite the test case.

    1. Any user data dependency

    2. Dependencies on test environment

    3. special setup

    4. dependencies on any anther test cases

    5. Test Steps Actual step to be followed or executed.

      1. Start with an order.
      2. Each step must have an expected result.
      3. All steps must be in the same sequence.
    6. Test Data. data that us used.

    7. Excepted Result.

    8. Actual result.

    9. Test case states. pass/fail/not applicable.

    10. Comments.

    11. Test case Priority -(Critical/high/medium/low).

Bug reports

  1. Bug ID: (problem , module Environment)
  2. Bug Title.
  3. Steps.
  4. Expected Result.
  5. Actual Result.
  6. Severity. write the importance of the bug for the user depending on SRS (Showstopper/critical/height/medium/low)
  7. priority ()
  8. Attachment(Screen shot/Recorded Video)

    Bug life cycle

  9. Tester finds bug.
  10. Developer analyze the bug(fixed/not a bug/need information/non reproducible)

Bug Statuses

  1. Fixed.
  2. Deferred.
  3. need information.
  4. not producible
  5. Duplicate
  6. not a bug
  7. known issue

Experience-based techniques

informal

This picture is show a list of Testing Technique : 1*hLerGVhDuDG5RZIUoUQvQg

Test Management

  1. Test organization.
  1. Developer(same project).
  2. Developer(not the author).
  3. independent testers inside the organization.
  4. independent testers out side the organization.
  5. independent testers specialist( visibility tester , security tester, certification testers)
  1. Test planning and Estimation.
  2. Test progress Monitoring and control.
  3. configuration management.
  4. Risk and Testing.
  5. Incident Management.

N|Solid

How To Install Software Needed

Install git

Minimum System Requirements:

Installing Java for Android Studio:

Before you install the Android Studio IDE, you need to make sure your Ubuntu installation is armed and ready with the recommended Java development kit for Android Studio – Oracle JDK.

To check the version of Java

$ java --version

If you don’t have Java installed, the output should be something like: N|Solid

Note: Make sure that you have updated the Advanced Package Tool (APT) before you move forward to install OpenJDK.

Install OpenJDK on Ubuntu

$ sudo apt install openjdk-14-jdk

All you have to do now is to set the “JAVA_HOME” and “PATH” environment variables and then you are done.

$ export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64
$ export JAVA_HOME
$ PATH=$PATH:$JAVA_HOME
$export PATH

Save the bash file, restart the terminal, and type echo $JAVA_HOME to make sure the path is properly set.

N|Solid

Installing Android Studio From The Ubuntu Software Center

Locate the Ubuntu Software Center icon in your taskbar and use the search functionality to find Android Studio. Click install and let it download and run initial setup. N|Solid

Install Flutter SDK on Ubuntu

System requirun the following command to begin signing licenses. rements

Install Flutter using snapd

$ sudo snap install flutter --classic

use the following command to display your Flutter SDK path:

$ flutter sdk-path

Run flutter doctor

$ flutter doctor
[-] Android toolchain - develop for Android devices
    • Android SDK at /Users/obiwan/Library/Android/sdk
    ✗ Android SDK is missing command line tools; download from https://goo.gl/XxQghQ
    • Try re-installing or updating your Android SDK,
      visit https://docs.flutter.dev/setup/#android-setup for detailed instructions.

Install Android SDK Command-line Tools (latest)

On your Android Studio Project, click on the File and then “Settings“. N|Solid

Select Appearance & Behavior > System Settings > Android SDK > SDK Tools

Check the box given for “Android SDK Command-line Tools (latest)” and then press the OK button

N|Solid

Agree to Android Licenses

run the following command to begin signing licenses.

 $ flutter doctor --android-licenses

Set up an editor

N|Solid

Backend

Install Node.js and npm

$ sudo apt update
$ sudo apt install nodejs npm
$ nodejs --version

Node JS

Install Visual studio code

Install MongoDB

How to git project from GitHub

$ git clone https://github.com/omarokasha1/TheFirstProject.git

Which libraries you used through the development process?

Build Status

packages in development environment

-  `dotenv` to store constant strings like database URL connection
-  `modemon` when click on ctrl + s restart the server automatically

The code is fully documented

7 Learning Process: State Management (Riverpod)

N|Solid

Riverpod

A state-management library that:

Build Status Build Status Build Status

package name description
Build Status Allows using both flutter_hooks and Riverpod together.
Build Status A basic way of using Riverpod for Flutter applications
Build Status A version of Riverpod with all the classes related to Flutter stripped out.

For widgets to be able to read providers, we need to wrap the entire application in a "ProviderScope" widget.

void main() {
  runApp(ProviderScope(child: MyApp(),),);
}

Providers

Providers are the most important part of a Riverpod application. A provider is an object that encapsulates a piece of state and allows listening to that state.

Creating a provider

final myProvider = Provider((ref) =>MyValue());

in Riverpod we can have two providers expose a state of the same "type":

final cityProvider = Provider((ref) => 'London');
final countryProvider = Provider((ref) => 'England');

Provide data:

Type of Provider

Advantages of RiverPod

BackEnd #3

We need to Document ( Installation - Usage - Hello World Example - Links for DOcumentation for each one ) : 1)Node JS Installation https://nodejs.org/en/docs/guides/getting-started-guide/ node 1 node 2 node 3

1) Express JS Installation • mkdir myapp • cd myapp • npm init • npm install express –save Hello world Example https://expressjs.com/en/starter/hello-world.html express

2) MongoDB Installation for ubuntu • wget -qO - https://www.mongodb.org/static/pgp/server-5.0.asc | sudo apt-key add - • sudo apt-get install gnupg • echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/5.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-5.0.list • sudo apt-get update • sudo apt-get install -y mongodb-org

Installation for windows • https://docs.mongodb.com/manual/tutorial/install-mongodb-on-windows/

3) IDEs

Tutorial Express js Documentation Express js Docs

Arabic tutorial API Tutorial
English Crash Course API Tutorial en

Which libraries you used through the development process?

Structure of code

there are 5 folders

Import Backend project to Visual studio code IDE

  1. Open Visual studio code IDE.
    • FileOpenFloderChoosing the project from the device
  2. Click project to import to Visual studio code

Run the project on a local Server

// copmresed requests app.use(compression())

// import register const usersRegister = require('./routes/register') app.use('/register', usersRegister) // import login const usersLogin = require('./routes/login') app.use('/login', usersLogin) // import profile const userProfile = require('./routes/profile') app.use('/profile', userProfile) // import changepassword const changePassword = require('./routes/changePassword') app.use('/api/changePassword', changePassword) // import courses const newCourse = require('./routes/courses') app.use('/api/course', newCourse)

// if write invalide url or end point send to user an error message app.all('*', (req, res, next) => { res.status(404).json({ status: 'false', message: 'Page not found !' }) }) // listen on port 8080 local host app.listen(8080, () => logger.info('server started 8080 ....'))


# Build User Schema 
###### You can add or remove any attribute
- userName must be in lowercase to be unique and make all users name completely different   
```sh
const UserSchema = new mongoose.Schema({
    userName: { type: String,unique:true, required: true, lowercase:true,minlength: 3, maxlength: 44 },
    email: { type: String, required: true, maxlength: 254 },
    password: { type: String, required: true, minlength: 8, maxlength: 1024 },
    phone: { type: Number, unique: true, minlength: 11, maxlength: 11 },
    isAdmin: { type: Boolean }m
 userEducation:  {
        university: { type: String, },
        major: { type: String, },
        faculty: { type: String, },
        experince: { type: String, },
        grade: { type: String, },
        interest: 
            [{type:String}]

    } ,
})

Schema validation using joi package

You can add or remove any attribute from your schema

}


```sh
//*validation on user inputs in login
function validateUserLogin(user) {
    const JoiSchema = Joi.object({

        email: Joi.string().email().min(3).max(25).required(),

        password: Joi.string().min(8).max(512).required()

    }).options({ abortEarly: false });

    return JoiSchema.validate(user)
}

Build Registration

if (user) { return res.status(200).json({ status: 'false', message: 'email already in use' }) }

- You can change any required attribute form schema the change the message
```sh
let user = await Users.findOne({ userName }).lean()

if (user) {
return res.status(200).json({ status: 'false', message: 'userName already in use' })
}

Build Login

module.exports =function (req, res, next) {
    // get the token from header called x-auth-token 
    const token = req.header('x-auth-token')
    if (!token) {
        res.status(401).send('access denied not auth......')
    }

    try {
        // decode the token to get the user info using `jwt.verify` from package jsonwebtoken
        const decodeToken = jwt.verify(token, 'privateKey')
        req.user = decodeToken
        next()

    } catch (er) {
        res.status(400).send('wrong token ......')
    }
}

getCourses middleware

module.exports = async function getCourses(req, res, next) {
    let course
    try {
 // find the courses with author
      course = await Course.find().populate('author','-__V').select('-__v')
      if (!course) {
        return res.status(200).json({ status: 'false', message: 'Cannot find courses' })
      }
      res.course = course
    } catch (err) {
      return res.status(500).json({ message: err.message })
    }

    res.course = course
    next()
  }

Change Password

change password inside the app for user that logged in

router.post('/', async (req, res) => {
    // take the password from user and validate it
    const { password: plainTextPassword } = req.body

    // take the token from header
    const token = req.header('x-auth-token')

    // validate the password if not string
    if (!plainTextPassword || typeof plainTextPassword !== 'string') {
        return res.status(200).json({ status: 'false', message: 'Invalid password' })
    }
    // validate the password if less than 8 char
    if (plainTextPassword.length < 8) {
        return res.status(200).json({
            status: 'false',
            message: 'Password too small. Should be atleast 8 characters'
        })
    }

    try {
        // decode the token to get user data
        const user = jwt.verify(token, 'privateKey')
        console.log(user)

        // get user id 
        const id = user.id
        console.log(id)

        // incrypt new password
        const newPassword = await bcrypt.hash(plainTextPassword, 10)

        // find the user by id and change the password
        await User.updateOne(
            { _id: id },
            {
                $set: { password: newPassword }
            }
        )
        res.status(200).json({ status: 'ok', message: 'password changed' })
    } catch (error) {
        res.json({ status: 'false', message: error.message })
    }
})

Build Profile

middleware auth check first if user logged in and have a token

get('/', auth, async (req, res) => {
    // find the user info by his id and not show the password at response using `select`
    const profile = await User.findById(req.user.id).select('-password -__v')

    res.json({ profile })
})

Build Course Schema

# Build Get Courses 

```sh
// Getting all
//* using getcourses middleware
router.get('/',getCourses, async (req, res) => {
  res.status(200).json({status : "ok",courses:res.course})
})

@omda07 I am still waiting as we agreed yesterday to have some Examples based on each questions to understand what exactly to change for example :

check in database by any required attribute you want from schema for example by email let user = await Users.findOne({ email }).lean()

if (user) { return res.status(404).json({ status: 'false', message: 'email already in use' }) }

You can make it like :

let user = await Users.findOne({ username }).lean()

if (user) { return res.status(404).json({ status: 'false', message: 'email already in use' }) }

To change the feedback message you can change here from

if (user) { return res.status(404).json({ status: 'false', message: 'email already in use' }) }

to if (user) { return res.status(404).json({ status: 'false', message: 'Hi, This is an Error' }) }


What is the 10 here ? You need to clear in the comments of the code what is each value refer to


userName: { type: String, required: true, minlength: 3, maxlength: 44 }, email: { type: String, required: true, maxlength: 254 },

How can I add more validation to ensure for example : 1) the Username can't start with Sympols or Numbers 2) Username can't have spaces 3) Username can't be duplicated like email Live while I am writing on Flutter GUI I validate if this username is used before In the database or not . To make it more clear I am writing first char "O" this less than 3 Paramters the FLutter Team will Raise flag that is less than 3 Char but after haveing for example "OOO" how we check instant without click on registration button and send that this username is booked from example . 4) In username is "OOO" is different from "ooo" is the validation function compare with taking in consideration the Capital of the Chars ?


}).options({ abortEarly: false });

What is this line refer to ?


https://github.com/omarokasha1/TheFirstProject/blob/186e8bbef167fa6f0cbbd9b7fcc79bffa3498e77/loginAndRegister/server.js

Where is the documentation / Comments for this Code ?


After Have a some time in the backend code here is my Thoughts :

It is Very Important @omda07 and @mirette3 to have next Documentation : 1) What is the Structure of the Code 2) What is automatic Generated by tools and We didn't edit or Developed anything at and What we changed in some files and what we developed ? 3) I can see that in this path https://github.com/omarokasha1/TheFirstProject/tree/backend/loginAndRegister we have 5 Folders and 5 FIles what is the usage from each one ? 4) What is these status Numbers ? What are they referring to ? we need a table with the definition of each number . 5) We need a table of definition that will have a keyword like subscriber ? 6) Check Change Password Code , you need to make a lot of comments with some questions like :

Again @omda07 and @mirette3 We need to have a skill called beginner mindset that will enable us to help others understand the code without making them study everything to can easily make all possible edits .

**### _

_**

Login & Register & Forget Password in the Same Screen #8

I would Thank @youssefelgebaly about his Document about Markdown to display this issue like awesome 😊

Flutter Update 2.10 : Windows #9

Flutter 2.10 Support Windows

Today, we’re thrilled to announce the full availability of support for Windows apps for Flutter in stable builds.

Build Status

Learning Process : Performance and Optimization #11

Performance

Figma Screens #13

On boarding Screen

welcome page display first time, when we launch the app. it contains two buttons (for login and sign-up) and four page-view each one has animation image and two text. welcome

Log in Screen

user open this screen to login if he already have an account. it contains two text-field (for email and password) and two button (for login and sign-up) login

Sign-Up Screen

user open this screen if he didn’t have an account. it contains five text-field(for email,username,password,confirm password and phone) and two buttons(for signup and login) signup

Forget password Screen

user open this screen if he forget password. it contains one text-filed for email and two buttons (resent password and login) forget

User Home Screen

home screen display when user login or sign up it includes user courses ,recommendation courses and top courses it contains app bar(have two icons for drawer and notifications) , flexible space (have text field and text) and three list-view.builder each one has numbers of cards (scroll in horizontal) home

Drawer

drawer display in app bar include all information of user such as profile , courses,setting ..etc. drawer

Search result

search

Notification screen

notification

Profile & Edit Profile screens

It includes personal and education information. to view profile the right screen while display and when you want to edit your profile the second screen will display. profile

Courses Screen

if user already enrolled in course the right screen will display other wise the left screen will display. courses

My Learning Screen

this screen includes my courses, tracks,wish-list courses , pending courses and archived courses. mylearning

Account setting screen

to change password open this screen accountsettings

Author Courses

authorcourses

Create Courses & modules

createcourse

my courses , tracks , modules

creats

Author public profile

authorprofile

How do pages communicate with each other

screens

lms

Flutter Documetation Task #15

The Flutter Code Structure

Naming method

Rely on small letters and separate words with _

layout file

This file includes a fixed screen to which the bottom navigation bar or the appbar can be added, and moving between more than one screen in the body

Models

This file includes models for each screen stored in the data used in this screen in short is the data warehouse that is used

Modules

This file includes screen files from widget and state management

C++ and Python Code #17

Problem Statement :

How to make automated testing through running some scripts


Technology Used :

Python and C++ as these are the Languages I can use Easily and Can support with them

In Python :

I used Python Requests and Json Technology to Communiate with the API

In C++ :

I used C++ CPR "CURL FOR HUMAN" and I used Nomral Libraries and An Important Hint to Run the Project you need to focus over the Makefile Technology


Setup Python3 Environment over Linux :

sudo apt-get install geany

Python Code :

This code to test and register a limited number of Users to the API

Thanks to @mirette3 a miswriting words has been fixed


# Adding Libraries that we will use in our Program : 

import requests 
# For Importing Library Requests
import json 
# For Importing Library Json

# ------------------------------------------------------------

# Test Connection to server

response = requests.get("http://10.5.62.214:8080/") 
# make HTTP Get Request to check if the Server Live or Not

print(response)
# print the Response of the Server which usually will be Status 200 

# ------------------------------------------------------------

# We need to start automating Register to the API 
# Through Using a While Loop we will have a Counter inside that will break the loop after reaching special Number 
# Through the Loop the Application will send to the Api the Needed Data using Requests Function and we will receive the response and validate it
# API need to send to it a Unique userName , Email , Phone 
# So we Fixed the username and Email through a variable called Keyword
# Validation over the Phone Number is the number must be 11 Number through a Fixed Variable will changed everytime based on the counter

keyword = 'omar'
# The Variable Used to create the userName and Email

Phonee =44140002000*2
# The Variable used to create the Phone Number will call it Phonee

i=0
# Initiate the Counter 

while 1:
  # Starting of the Loop
  # Must take in consideration the Spaces as Python Senstive for the Spaces 

  email=keyword+str(i)+"@[gmail.com](http://gmail.com/)"
  # Create Email Variable using the Keyword and the Current counter and @gmail.com for example omar0@gmail.com

  password="1111111111111"+str(i)
  # Create Password Variable using a fixed string which is "1111111111111" and the Current counter 

  phone=str(Phonee+i)
   # Create Phone Variable using the sum of  Phonee and Current counter 

  username=keyword+str(i)
   # Create username Variable using the String sum of  keyword and Current counter as String which will be omar0 

  r = requests.post('http://10.5.62.214:8080/api/register', json={"email":email,"password":password,"phone":phone,"userName":username})
  # Here Code make a POST request by sending to the API 'http://10.5.62.214:8080/api/register' a json body as mentioned above and store the response at " r "

  #print(r)
  # Print all the response

  print(r.json())
  # print the JSON Content

  x=r.json()
  # store the JSON Content inside new Variable 

  print(x['token'])
  # print the attribute that have the key token

  i=i+1
  # Increment the Counter

  if(i==1000000):
    break
  # Break the Loop if we reached that Number of Rounder or Users Registers 

------------------------------------------------------------

Setup C++Environment over Linux :

Installation gcc

 sudo apt-get install gcc

Installation g++

 sudo apt-get install g++

Installation eclipse for C++

> Visit the URL Below

https://www.eclipse.org/downloads/packages/

image

> Search for Eclipse for C++

image

> Download Linux [x86_64]

> After Downloading unzip the file and open the folder and double click on eclipse file

> Accept all Eclipse Setup for Location to be used to save projects

> From FIle > New Project > C++ Project > Cmake > Cmake Project > Give the Project name > Then hit finish

> The Reason Behind Using Cmake to can download libraries online and add them to the project meanwhile it will help you in building the project easily and can help in future to add more libraries and even export project to be executed on other devices Thanks to @KareemAhmed22 this has been added

> You will find at the left Project Explore that have 2 Main files : Your Project name .cpp and CMakeList.txt and Binaries and Build Folder

Your Code will be Inside the Your Project name .cpp To Download Libraries Online and Use it inside your Project we will use in future CMakeList.txt Build Folder Where the Downloaded Libraries will built with their dependences Binaries Folder for the Executables Files

After Understanding Eclipse Let's Add our Library " cpr C++ "

First of All Visit this repo on github as this library we are going to use and have a look at readme :

https://github.com/libcpr/cpr

image

You will find out Label for Usage :

image

You will find some CMakeList.txt Scripts

You will copy them and paste at your CMakeFile.txt at your project inside Eclipse Below is my CMakeFile.txt you can use it directly but Every Omar Word Replace it in the next code with your Project name

cmake_minimum_required (VERSION 2.6)

project (omar)

add_executable(omar omar.cpp)
include(FetchContent)
FetchContent_Declare(cpr GIT_REPOSITORY https://github.com/libcpr/cpr.git
                         GIT_TAG beb9e98806bb84bcc130a2cebfbcbbc6ce62b335) # The commit hash for 1.7.2. Replace with the latest from: https://github.com/libcpr/cpr/releases
FetchContent_MakeAvailable(cpr)

target_link_libraries(omar PRIVATE cpr::cpr)

Important

You will face Problem to Make the CMakeFile.txt with each build to ensure that any update their will bounce direct back to your project.

To Solve This Check the Stackoverflow Issue and Try to follow it .

https://stackoverflow.com/questions/12574187/eclipse-cdt-no-rule-to-make-target-all

Screenshot from 2022-02-14 20-17-14

Screenshot from 2022-02-14 20-17-18

After this. When you are going to run the Project This will run automatic to ensure all libraries are supplied and up to date

C++ Code :

 // Libraries Used in the Code

#include <iostream>
// Standard Library for Input Output Operations
#include <cpr/cpr.h>
// Our Main Library for Communication with the API
#include <string>
//Handling the Strings in the Code
#include <thread>
// To make Threads to run Features Parallel
#include <sstream>
// we used it here to can Make stream to store the Phone Number then Transform it to String as Setpercision function works only with streams
#include <iomanip>
// to can use setprecision function to work to can get the float without decimal point
using namespace std;
// Using the Standard Namespace

// Main Function Used to register Accounts
// This Fucntion take 3 Variables :
// The first Variable : Keyword which is the keyword that will manipulate the Username and Email
// The Second Variable : is K which is used for Creating Phone Number
// The Third Variable : is the Number of Iteration needed to be done

void omar (string keyword,double k,int iteration)
{
    // the loop that will help with register all needed users

    for(int i = 0 ; i < iteration;i++)
    {
            stringstream stream;
            // This is to make a new string stream object called stream

            stream << std::fixed << setprecision(0) << i+k;
            // Here we are saving at stream tha sum of i + k but taking in consideration that the percision is 0 which means no decimel point and std::fixed is for keep the accuracy of our double or float to 6 digits after the decimel.

            string phone = stream.str();

            // Save at a new variable called phone the string saved in stream

            string body = "{\"userName\":\""+keyword+to_string(i)+"\",\"email\":\""+keyword+to_string(i)+"@gmail.com\",\"password\":\"abdeceasdasd\",\"phone\":\""+phone+"\"}";

            // Here we store the json generated order to can send it in variable called Body 

            auto r = cpr::Post(cpr::Url{"http://10.5.62.214:8080/api/register"}
            ,
            cpr::Header{{"Content-Type","application/json"}}
            ,
            cpr::Body{body});

            // Here in cpr we use it to make POST request by giving it the Url that we are going to use which is http://10.5.62.214:8080/api/register
            // By Giving to cpr too that the header is Application Json and then send in the bodd the body we created

//  cout<<r.text <<endl;
    }
}

int main(int argc, char **argv) {

    // To make the Program run multiple times parallel we start using Threads

    // Next we will initiate 8 Threads 

    // thread working like this 

    // thread name_of_tread(function_you_are_going_to_run , function Variables )

    thread th1(omar, "xxxx",19091222334,1000);

    thread th2(omar, "xxxxx",29094222334,1000);

    thread th3(omar, "xxxxxx",39066222334,1000);

    thread th4(omar, "xxxxxxx",49042223341,1000);

    thread th5(omar, "xxxxxxxx",50042223341,1000);

    thread th6(omar, "xxxxxxxxx",60042223341,1000);

    thread th7(omar, "xxxxxxxxxx",70042223341,1000);

    thread th8(omar, "xxxxxxxxxxx",80042223341,1000);

    // Here we start launching the Threads 
    th1.join();
    th2.join();
    th3.join();
    th4.join();
    th5.join();
    th6.join();
    th7.join();
    th8.join();

    // THe program Automatic will close after finishing all threads
    return 0;
}

After Adding this code to your project in your C++ File inside Eclipse you will need to start Compile and Run it :

First you will need to build your Project and then Run it and TaDaaaaa You are Live :)

Enjoy!

------------------------------------------------------------

For Future Development :

C++ Project.zip