Merge remote-tracking branch 'EGUI/main' into main

This commit is contained in:
PolishPigeon 2022-06-18 01:15:44 +02:00
commit 000ab7fa40
39616 changed files with 4988811 additions and 0 deletions

92
EGUI/README.md Normal file
View File

@ -0,0 +1,92 @@
# EGUI_LAB1_KRZYSZTOF_RUDNICKI
## Getting started
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
## Add your files
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
```
cd existing_repo
git remote add origin https://gitlab-stud.elka.pw.edu.pl/egui22l/Krzysztof_Stefan_Rudnicki/egui_lab1_krzysztof_rudnicki.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://gitlab-stud.elka.pw.edu.pl/egui22l/Krzysztof_Stefan_Rudnicki/egui_lab1_krzysztof_rudnicki/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.

73
EGUI/lab1/.gitignore vendored Normal file
View File

@ -0,0 +1,73 @@
# This file is used to ignore files which are generated
# ----------------------------------------------------------------------------
*~
*.autosave
*.a
*.core
*.moc
*.o
*.obj
*.orig
*.rej
*.so
*.so.*
*_pch.h.cpp
*_resource.rc
*.qm
.#*
*.*#
core
!core/
tags
.DS_Store
.directory
*.debug
Makefile*
*.prl
*.app
moc_*.cpp
ui_*.h
qrc_*.cpp
Thumbs.db
*.res
*.rc
/.qmake.cache
/.qmake.stash
# qtcreator generated files
*.pro.user*
# xemacs temporary files
*.flc
# Vim temporary files
.*.swp
# Visual Studio generated files
*.ib_pdb_index
*.idb
*.ilk
*.pdb
*.sln
*.suo
*.vcproj
*vcproj.*.*.user
*.ncb
*.sdf
*.opensdf
*.vcxproj
*vcxproj.*
# MinGW generated files
*.Debug
*.Release
# Python byte code
*.pyc
# Binaries
# --------
*.dll
*.exe

207
EGUI/lab1/blogentry.cpp Normal file
View File

@ -0,0 +1,207 @@
#include "blogentry.h"
#include "ui_blogentry.h"
#include "universalFunctions.h"
#include <QDateTime>
#include <QJsonObject>
#include <QFile>
#include <QJsonDocument>
#include <QJsonArray>
blogEntry::blogEntry(QWidget *parent) :
QWidget(parent),
ui(new Ui::blogEntry)
{
editMode = false;
ui->setupUi(this);
ui -> editEntryButton -> setDisabled(true);
defineConnections();
}
void blogEntry::disableEdition()
{
ui -> textEdit -> setReadOnly(true);
ui -> lineEdit -> setReadOnly(true);
}
void blogEntry::enableEdition()
{
ui -> textEdit -> setReadOnly(false);
ui -> lineEdit -> setReadOnly(false);
}
void blogEntry::defineConnections() const
{
connect(ui -> pushButton, &QPushButton::clicked, this, &blogEntry::removeEntry);
connect(ui -> editEntryButton, &QPushButton::clicked, this, &blogEntry::editEntryClicked);
connect(ui -> saveEntry, &QPushButton::clicked, this, &blogEntry::saveEntryMethod);
}
void blogEntry::fillEntry(const QJsonObject &entry)
{
ui -> lineEdit -> setText(entry["title"].toString());
ui -> textEdit -> setText(entry["content"].toString());
ui -> dateTime -> setText(entry["datetime"].toString());
ui -> ownerID -> setText("Owner ID: " + userId);
}
void blogEntry::setUpBlogEntryFromJson(const QJsonObject &entry)
{
dateTime = entry["datetime"].toString();
fillEntry(entry);
disableEdition();
enableEditing();
}
blogEntry::~blogEntry()
{
delete ui;
}
void blogEntry::setUserId(const QString &userId)
{
qDebug() << "blogEntry id: " << userId;
this->userId = userId;
ui -> ownerID -> setText("Owner ID: " + userId);
}
void blogEntry::setBlogId(const QString &blogId)
{
this->blogId = blogId;
}
QJsonObject blogEntry::setDateTime(QJsonObject &entry)
{
QString Time = QTime::currentTime().toString();
QString Date = QDate::currentDate().toString();
entry["datetime"] = Time + " " + Date;
dateTime = Time + " " + Date;
ui -> dateTime -> setText( Time + " " + Date);
return entry;
}
void blogEntry::enableEditing()
{
ui -> saveEntry -> setDisabled(true);
ui -> editEntryButton -> setDisabled(false);
}
QJsonObject blogEntry::setEntry()
{
QJsonObject entry;
entry["title"] = ui -> lineEdit -> text();
entry = setDateTime(entry);
entry["content"] = ui -> textEdit -> toPlainText();
return entry;
}
void blogEntry::saveEntryMethod()
{
disableEdition();
QJsonObject blogsFile = readJsonFile("blogs.json");
QJsonObject blogEntryJson = blogsFile[blogId].toObject();
QJsonObject entry = setEntry();
QJsonArray items = blogEntryJson["items"].toArray();
items.append(entry);
saveItemToBlogEntryToBlogsFile(items, blogEntryJson, blogsFile);
enableEditing();
}
int blogEntry::findEntry(const QJsonArray &items)
{
int i = 0;
for(i = 0; i < items.size(); i++)
{
QJsonObject currentItem = items[i].toObject();
if(currentItem["datetime"].toString() == dateTime)
{
return i;
}
}
return -1;
}
QJsonArray blogEntry::removeEntryFromArray(const QJsonObject &blogEntryJson)
{
QJsonArray items = blogEntryJson["items"].toArray();
int entryI = findEntry(items);
if(entryI == -1)
{
return items;
}
items.removeAt(entryI);
return items;
}
void blogEntry::removeEntry()
{
QJsonObject blogsFile = readJsonFile("blogs.json");
QJsonObject blogEntryJson = blogsFile[blogId].toObject();
QJsonArray items = removeEntryFromArray(blogEntryJson);
saveItemToBlogEntryToBlogsFile(items, blogEntryJson, blogsFile);
this -> ~blogEntry();
}
void blogEntry::editEntry()
{
editMode = true;
enableEdition();
ui -> saveEntry -> setDisabled(true);
ui -> editEntryButton -> setText("Save edit");
}
QJsonArray blogEntry::addEdit(const QJsonObject &blogEntryJson)
{
QJsonArray items = blogEntryJson["items"].toArray();
for(int i = 0; i < items.size(); i++)
{
QJsonObject currentItem = items[i].toObject();
if(currentItem["datetime"].toString() == dateTime)
{
currentItem["title"] = ui -> lineEdit -> text();
currentItem["content"] = ui -> textEdit -> toPlainText();
items.removeAt(i);
items.append(currentItem);
break;
}
}
return items;
}
void blogEntry::saveItemToBlogEntryToBlogsFile(QJsonArray &items, QJsonObject &blogEntryJson, QJsonObject &blogsFile)
{
blogEntryJson.insert("items", items);
blogsFile.insert(blogId, blogEntryJson);
saveJsonFile(blogsFile, "blogs.json");
}
void blogEntry::saveEntry(QJsonObject &blogEntryJson, QJsonObject &blogsFile)
{
QJsonArray items = addEdit(blogEntryJson);
saveItemToBlogEntryToBlogsFile(items, blogEntryJson, blogsFile);
}
void blogEntry::saveEditedEntry()
{
disableEdition();
editMode = false;
ui -> editEntryButton -> setText("Edit Entry");
QJsonObject blogsFile = readJsonFile("blogs.json");
QJsonObject blogEntryJson = blogsFile[blogId].toObject();
saveEntry(blogEntryJson, blogsFile);
}
void blogEntry::editEntryClicked()
{
if(!editMode) editEntry();
else saveEditedEntry();
}

57
EGUI/lab1/blogentry.h Normal file
View File

@ -0,0 +1,57 @@
#ifndef BLOGENTRY_H
#define BLOGENTRY_H
#include <QWidget>
#include <QJsonObject>
#include <QFile>
#include <QJsonDocument>
namespace Ui {
class blogEntry;
}
class blogEntry : public QWidget
{
Q_OBJECT
public:
explicit blogEntry(QWidget *parent = nullptr);
~blogEntry();
void setUserId(const QString &userId);
void setBlogId(const QString &blogId);
void setUpBlogEntryFromJson(const QJsonObject &entry);
private slots:
private:
void removeEntry();
void enableEdition();
void disableEdition();
void saveEntryMethod();
void enableEditing();
void editEntry();
void saveEditedEntry();
void defineConnections() const;
void editEntryClicked();
void saveEntry(QJsonObject &blogEntryJson, QJsonObject &blogsFile);
void saveItemToBlogEntryToBlogsFile(QJsonArray &items, QJsonObject &blogEntryJson, QJsonObject &blogsFile);
void fillEntry(const QJsonObject &entry);
int findEntry(const QJsonArray &items);
QJsonArray removeEntryFromArray(const QJsonObject &blogEntryJson);
QJsonArray addEdit(const QJsonObject &blogEntryJson);
QJsonArray getItemsList();
QJsonObject setDateTime(QJsonObject &entry);
QJsonObject setEntry();
Ui::blogEntry *ui;
QString userId;
QString blogId;
QString dateTime;
bool editMode;
};
#endif // BLOGENTRY_H

85
EGUI/lab1/blogentry.ui Normal file
View File

@ -0,0 +1,85 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>blogEntry</class>
<widget class="QWidget" name="blogEntry">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>250</width>
<height>250</height>
</rect>
</property>
<property name="minimumSize">
<size>
<width>0</width>
<height>250</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>16777215</width>
<height>250</height>
</size>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
<layout class="QFormLayout" name="formLayout">
<item row="0" column="1">
<widget class="QLineEdit" name="lineEdit">
<property name="text">
<string>Title</string>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QLabel" name="ownerID">
<property name="text">
<string>ownerID</string>
</property>
</widget>
</item>
<item row="2" column="1">
<widget class="QLabel" name="dateTime">
<property name="text">
<string>Date Time</string>
</property>
</widget>
</item>
<item row="3" column="1">
<widget class="QTextEdit" name="textEdit">
<property name="readOnly">
<bool>false</bool>
</property>
</widget>
</item>
<item row="4" column="1">
<widget class="QPushButton" name="saveEntry">
<property name="text">
<string>Save Entry</string>
</property>
<property name="flat">
<bool>false</bool>
</property>
</widget>
</item>
<item row="5" column="1">
<widget class="QPushButton" name="pushButton">
<property name="text">
<string>Remove Entry</string>
</property>
</widget>
</item>
<item row="6" column="1">
<widget class="QPushButton" name="editEntryButton">
<property name="text">
<string>Edit Entry</string>
</property>
</widget>
</item>
</layout>
</widget>
<resources/>
<connections/>
</ui>

79
EGUI/lab1/blogsview.cpp Normal file
View File

@ -0,0 +1,79 @@
#include "universalFunctions.h"
#include "blogsview.h"
#include "ui_blogsview.h"
#include "blogentry.h"
#include "ui_blogentry.h"
#include <algorithm>
#include <QJsonObject>
#include <QFile>
#include <QJsonDocument>
#include <QJsonArray>
blogsView::blogsView(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::blogsView)
{
ui->setupUi(this);
defineConnections();
}
void blogsView::defineConnections() const
{
connect(ui -> actionCreate_new_Blog_entry, &QAction::triggered, this, &blogsView::createNewBlogEntry);
connect(ui -> actionExit, &QAction::triggered, this, &blogsView::exit);
}
blogsView::~blogsView()
{
delete ui;
}
void blogsView::setUserId(const QString &userId)
{
this->userId = userId;
}
void blogsView::setBlogId(const QString &blogId)
{
qDebug() << "blog id before set: " << blogId;
this->blogId = blogId;
qDebug() << "blog id after set: " << this->blogId;
displayBlogEntries();
}
void blogsView::createNewBlogEntry()
{
blogEntry *e = new blogEntry();
e -> setUserId(userId);
e -> setBlogId(blogId);
ui -> blogsLayout -> addWidget(e);
}
void blogsView::displayBlogEntriesLoop(const QJsonArray &blogEntries)
{
for(int i = 0; i < blogEntries.size(); i++)
{
QJsonObject entry = (blogEntries.at(i)).toObject();
createNewBlogEntry();
}
}
void blogsView::displayBlogEntries()
{
QJsonObject blogsFile = readJsonFile("blogs.json");
QJsonObject userBlog = blogsFile[blogId].toObject();
qDebug() << blogId;
qDebug() << userBlog["blogId"].toString();
QJsonArray blogEntries = userBlog["items"].toArray();
displayBlogEntriesLoop(blogEntries);
}
void blogsView::exit()
{
QApplication::quit();
}

34
EGUI/lab1/blogsview.h Normal file
View File

@ -0,0 +1,34 @@
#ifndef BLOGSVIEW_H
#define BLOGSVIEW_H
#include <QMainWindow>
namespace Ui {
class blogsView;
}
class blogsView : public QMainWindow
{
Q_OBJECT
public:
explicit blogsView(QWidget *parent = nullptr);
~blogsView();
void setUserId(const QString &userId);
void setBlogId(const QString &blogId);
private slots:
void displayBlogEntries();
void exit();
private:
void defineConnections() const;
void displayBlogEntriesLoop(const QJsonArray &blogEntries);
void createNewBlogEntry();
Ui::blogsView *ui;
QString userId;
QString blogId;
};
#endif // BLOGSVIEW_H

80
EGUI/lab1/blogsview.ui Normal file
View File

@ -0,0 +1,80 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>blogsView</class>
<widget class="QMainWindow" name="blogsView">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>600</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<layout class="QGridLayout" name="gridLayout">
<item row="0" column="0">
<widget class="QScrollArea" name="scrollArea">
<property name="widgetResizable">
<bool>true</bool>
</property>
<widget class="QWidget" name="scrollAreaWidgetContents">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>780</width>
<height>539</height>
</rect>
</property>
<layout class="QGridLayout" name="gridLayout_2">
<item row="0" column="0">
<layout class="QVBoxLayout" name="blogsLayout"/>
</item>
</layout>
</widget>
</widget>
</item>
</layout>
</widget>
<widget class="QStatusBar" name="statusbar"/>
<widget class="QMenuBar" name="menubar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>19</height>
</rect>
</property>
<widget class="QMenu" name="menuManageBlogEntires">
<property name="title">
<string>Blogs</string>
</property>
<addaction name="actionCreate_new_Blog_entry"/>
</widget>
<widget class="QMenu" name="menuExit">
<property name="title">
<string>App</string>
</property>
<addaction name="actionExit"/>
</widget>
<addaction name="menuManageBlogEntires"/>
<addaction name="menuExit"/>
</widget>
<action name="actionCreate_new_Blog_entry">
<property name="text">
<string>Create blog entry</string>
</property>
</action>
<action name="actionExit">
<property name="text">
<string>Exit</string>
</property>
</action>
</widget>
<resources/>
<connections/>
</ui>

40
EGUI/lab1/lab1.pro Normal file
View File

@ -0,0 +1,40 @@
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
CONFIG += c++17
# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \
blogentry.cpp \
blogsview.cpp \
login.cpp \
main.cpp \
mainwindow.cpp \
universalFunctions.cpp
HEADERS += \
blogentry.h \
blogsview.h \
login.h \
mainwindow.h \
universalFunctions.h
FORMS += \
blogentry.ui \
blogsview.ui \
login.ui \
mainwindow.ui
TRANSLATIONS += \
lab1_pl_PL.ts
CONFIG += lrelease
CONFIG += embed_translations
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

3
EGUI/lab1/lab1_pl_PL.ts Normal file
View File

@ -0,0 +1,3 @@
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="pl_PL"></TS>

91
EGUI/lab1/login.cpp Normal file
View File

@ -0,0 +1,91 @@
#include "login.h"
#include "ui_login.h"
#include "blogsview.h"
#include "mainwindow.h"
#include "universalFunctions.h"
#include <QFileDialog>
#include <QMessageBox>
#include <iostream>
#include <QJsonObject>
#include <QJsonDocument>
#include <QTextStream>
login::login(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::login)
{
ui->setupUi(this);
defineConnections();
}
login::~login()
{
delete ui;
}
void login::defineConnections() const
{
connect(ui -> loginButton, &QPushButton::clicked, this, &login::loginUser);
connect(ui -> registerButton, &QPushButton::clicked, this, &login::goRegister);
connect(ui -> actionExit, &QAction::triggered, this, &login::exit);
connect(ui -> actionLogin, &QAction::triggered, this, &login::loginUser);
connect(ui -> actionRegister, &QAction::triggered, this, &login::goRegister);
}
void login::exit() const
{
QApplication::quit();
}
void login::goRegister()
{
MainWindow *r = new MainWindow();
r -> show();
hide();
}
void login::loginSuccessful(const QString &id, const QString &blogId)
{
qDebug() << "blog id: " << blogId;
blogsView *b = new blogsView();
b -> setUserId(id);
b -> setBlogId(blogId);
b -> show();
hide();
}
QString login::findCurrentBlogId(const QJsonObject &blogs, const QString &id)
{
QString currentBlogId = "";
QStringList keys = blogs.keys();
for(int i = 0; i < keys.size(); i++)
{
QJsonObject currentBlog = blogs[keys.at(i)].toObject();
if(currentBlog["ownerId"] == id)
{
currentBlogId = (currentBlog.take("blogId")).toString();
return currentBlogId;
break;
}
}
return "";
}
void login::loginUser()
{
QJsonObject users = readJsonFile("user.json");
QJsonObject blogs = readJsonFile("blogs.json");
QString id = ui->inputLoginID_2->text();
if (!idExists(id, users, "THIS USER ID DOES NOT EXIST!", false)) return;
QString enteredPassword = ui->inputPassword->text();
if (!sameString(enteredPassword, "password", users, "WRONG PASSWORD!")) return;
QString currentBlogId = findCurrentBlogId(blogs, id);
if (stringEmpty(currentBlogId, "COULD NOT FOUND BLOG ID FOR THIS LOGIN \n SOMETHING WENT TERRIBLY WRONG WITH JSON FILE!")) return;
loginSuccessful(id, currentBlogId);
}

30
EGUI/lab1/login.h Normal file
View File

@ -0,0 +1,30 @@
#ifndef LOGIN_H
#define LOGIN_H
#include <QMainWindow>
namespace Ui {
class login;
}
class login : public QMainWindow
{
Q_OBJECT
public:
explicit login(QWidget *parent = nullptr);
~login();
private slots:
private:
void loginUser();
void loginSuccessful(const QString &id, const QString &blogId);
void defineConnections() const;
void goRegister();
void exit() const;
QString findCurrentBlogId(const QJsonObject &blogs, const QString &id);
Ui::login *ui;
};
#endif // LOGIN_H

103
EGUI/lab1/login.ui Normal file
View File

@ -0,0 +1,103 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>login</class>
<widget class="QMainWindow" name="login">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>600</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<layout class="QFormLayout" name="formLayout">
<item row="0" column="0" colspan="2">
<widget class="QLabel" name="label">
<property name="text">
<string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p align=&quot;center&quot;&gt;&lt;span style=&quot; font-size:72pt;&quot;&gt;Login&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property>
</widget>
</item>
<item row="1" column="0" colspan="2">
<widget class="QLabel" name="label_2">
<property name="text">
<string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p align=&quot;center&quot;&gt;&lt;span style=&quot; font-size:36pt;&quot;&gt;ID&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property>
</widget>
</item>
<item row="2" column="0" colspan="2">
<widget class="QLineEdit" name="inputLoginID_2"/>
</item>
<item row="3" column="0" colspan="2">
<widget class="QLabel" name="label_3">
<property name="text">
<string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p align=&quot;center&quot;&gt;&lt;span style=&quot; font-size:36pt;&quot;&gt;Password&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property>
</widget>
</item>
<item row="4" column="0" colspan="2">
<widget class="QLineEdit" name="inputPassword">
<property name="echoMode">
<enum>QLineEdit::Password</enum>
</property>
</widget>
</item>
<item row="5" column="0" colspan="2">
<widget class="QPushButton" name="loginButton">
<property name="text">
<string>Login</string>
</property>
</widget>
</item>
<item row="6" column="0" colspan="2">
<widget class="QPushButton" name="registerButton">
<property name="text">
<string>Register</string>
</property>
</widget>
</item>
</layout>
</widget>
<widget class="QMenuBar" name="menubar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>19</height>
</rect>
</property>
<widget class="QMenu" name="menuApp">
<property name="title">
<string>App</string>
</property>
<addaction name="actionExit"/>
<addaction name="actionLogin"/>
<addaction name="actionRegister"/>
</widget>
<addaction name="menuApp"/>
</widget>
<widget class="QStatusBar" name="statusbar"/>
<action name="actionExit">
<property name="text">
<string>Exit</string>
</property>
</action>
<action name="actionLogin">
<property name="text">
<string>Login</string>
</property>
</action>
<action name="actionRegister">
<property name="text">
<string>Register</string>
</property>
</action>
</widget>
<resources/>
<connections/>
</ui>

46
EGUI/lab1/main.cpp Normal file
View File

@ -0,0 +1,46 @@
#include "mainwindow.h" // header file included, header files for the Notepad widget
#include "universalFunctions.h"
#include <QApplication> // handle widgets, events, mouse movement, feel of window,
// header files for QApplication
#include <QLocale>
#include <QTranslator>
#include <QFile>
#include <QJsonDocument>
// main function that is the entry point for all C and C++ based applications:
int main(int argc, char *argv[]) // all exectution begins here
{
QApplication a(argc, argv); // creates a QApplication object.
// This object manages application-wide resources and is necessary to run
// any Qt program that uses Qt Widgets. It constructs an application object
// with argc command line arguments run in argv
QTranslator translator;
const QStringList uiLanguages = QLocale::system().uiLanguages();
for (const QString &locale : uiLanguages) {
const QString baseName = "lab1_" + QLocale(locale).name();
if (translator.load(":/i18n/" + baseName)) {
a.installTranslator(&translator);
break;
}
}
MainWindow w; // we create main application object
// This is the object for which the wizard created the class and the UI file.
// The user interface contains visual elements that are called widgets in Qt.
// Examples of widgets are text edits, scroll bars, labels, and radio buttons.
// A widget can also be a container for other widgets;
// va dialog or a main application window, for example.
w.show(); // we display it
// The following line shows the mainWindow widget on the screen in its own window.
// Widgets can also function as containers.
// An example of this is QMainWindow which often contains several types of widgets.
// Widgets are not visible by default; the function show() makes the widget visible.
return a.exec(); // put app into loop where events in application are going to happen
// The following line makes the QApplication enter its event loop.
// When a Qt application is running,
// events are generated and sent to the widgets of the application.
// Examples of events are mouse presses and key strokes.
}

121
EGUI/lab1/mainwindow.cpp Normal file
View File

@ -0,0 +1,121 @@
#include "mainwindow.h" // Notepad class header file that was generated by the wizard
#include "ui_mainwindow.h"// UI header file that was generated by the uic tool
#include "login.h"
#include "universalFunctions.h"
#include <QFileDialog>
#include <QMessageBox>
#include <iostream>
#include <QJsonObject>
#include <QJsonDocument>
#include <QTextStream>
#include <QJsonArray>
MainWindow::MainWindow(QWidget *parent) // class definition, constructor
: QMainWindow(parent) // calls qmainwindow parent constructor we have,
// base class for the MainWindow class:
, ui(new Ui::MainWindow) // create ui class and assign to ui member
// creates the UI class instance and assigns it to the ui member:
{
ui->setupUi(this); // setup user interface
defineConnections();
}
void MainWindow::defineConnections() const
{
connect(ui -> loginButton, &QPushButton::clicked, this, &MainWindow::goToLogin);
connect(ui -> pushButton, &QPushButton::clicked, this, &MainWindow::saveRegisteredUser);
connect(ui -> actionExit, &QAction::triggered, this, &MainWindow::exit);
connect(ui -> actionLogin, &QAction::triggered, this, &MainWindow::goToLogin);
}
void MainWindow::exit() const
{
QApplication::quit();
}
MainWindow::~MainWindow()
{
delete ui; // in the destructor, we delete the ui
}
QJsonObject MainWindow::createUserObject(const QString &mail, const QString &password, const QString &userId) const
{
QJsonObject user;
user["userId"] = userId;
// userId - unique user id - text obtained from the user during user registration
user["email"] = mail;
// email - e-mail address of the user
user["password"] = password;
// password - password provided by the user
return user;
}
QJsonObject MainWindow::insertUserObject(QJsonObject &users, const QString &id)
{
QString mail = ui->inputMail->text();
QString password = ui->inputPassword->text();
QJsonObject user = createUserObject(mail, password, id);
users.insert(id, user);
return users;
}
QJsonObject MainWindow::createBlogObject(const QString &id, const QString &ownerId) const
{
QJsonObject blog;
blog["blogId"] = id;
QString title = ui -> inputBlogTitle -> text();
blog["title"] = title;
blog["ownerId"] = ownerId;
QJsonArray items;
blog["items"] = items;
return blog;
}
QJsonObject MainWindow::insertBlogObject(QJsonObject &blogs, const QString &blogId, const QString &ownerId)
{
QJsonObject blog = createBlogObject(blogId, ownerId);
blogs.insert(blogId, blog);
return blogs;
}
void MainWindow::saveFiles(QJsonObject &users, QJsonObject &blogs)
{
saveJsonFile(blogs, "blogs.json");
saveJsonFile(users, "user.json");
}
void MainWindow::registerUser(QJsonObject &users, QJsonObject &blogs, const QString &id, const QString &blogId)
{
users = insertUserObject(users, id);
blogs = insertBlogObject(blogs, blogId, id);
saveFiles(users, blogs);
}
void MainWindow::saveRegisteredUser()
{
QJsonObject blogs = readJsonFile("blogs.json");
QJsonObject users = readJsonFile("user.json");
QString id = ui->inputId->text();
if (stringEmpty(id, "THIS USER ID IS EMPTY!")) return;
if (idExists(id, users, "THIS USER ID IS ALREADY TAKEN!", true)) return;
QString blogId = ui -> inputBlogID->text();
if (stringEmpty(blogId, "THIS BLOG ID IS EMPTY!")) return;
if (idExists(blogId, blogs, "THIS BLOG ID IS ALREADY TAKEN!", true)) return;
registerUser(users, blogs, id, blogId);
}
void MainWindow::goToLogin()
{
login *l = new login();
l -> show();
hide();
}

47
EGUI/lab1/mainwindow.h Normal file
View File

@ -0,0 +1,47 @@
#ifndef MAINWINDOW_H // make sure that header is not loaded more than once
#define MAINWINDOW_H
#include <QMainWindow> // Provide main application window in wchich user interface is build
// We can add more functionality using #include <Q...>
#include <QJsonObject>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; } // we are saying that we want to use standard ui namespace
// tied to our UI file "mainwindow.ui"
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT // base class for all qt objects we work with
// The class declaration contains the Q_OBJECT macro.
// It must come first in the class definition, and declares our class as a QObject.
// Naturally, it must also inherit from QObject.
// A QObject adds several abilities to a normal C++ class.
// Notably, the class name and slot names can be queried at runtime.
// It is also possible to query a slot's parameter types and invoke it.
public:
MainWindow(QWidget *parent = nullptr); // constructor, we pass nullptr so no parents
// (top-level widget)
~MainWindow(); // destructor, free resources
private slots:
private:
void newDocument() const;
void open() const;
void saveRegisteredUser();
void goToLogin();
void defineConnections() const;
void registerUser(QJsonObject &users, QJsonObject &blogs, const QString &blogId, const QString &id);
QJsonObject createUserObject(const QString &mail, const QString &password, const QString &userId) const;
QJsonObject createBlogObject(const QString &id, const QString &ownerId) const;
void exit() const;
QJsonObject insertUserObject(QJsonObject &users, const QString &id);
void saveFiles(QJsonObject &users, QJsonObject &blogs);
QJsonObject insertBlogObject(QJsonObject &blogs, const QString &blogId, const QString &ownerId);
Ui::MainWindow *ui; // we point to ui class "mainwindow.ui"
};
#endif // MAINWINDOW_H

146
EGUI/lab1/mainwindow.ui Normal file
View File

@ -0,0 +1,146 @@
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>600</height>
</rect>
</property>
<property name="windowTitle">
<string>MainWindow</string>
</property>
<widget class="QWidget" name="centralwidget">
<layout class="QFormLayout" name="formLayout">
<item row="0" column="0" colspan="2">
<widget class="QLabel" name="label">
<property name="text">
<string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p align=&quot;center&quot;&gt;&lt;span style=&quot; font-size:48pt;&quot;&gt;Register&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property>
</widget>
</item>
<item row="6" column="0" colspan="2">
<widget class="QLineEdit" name="inputId">
<property name="toolTip">
<string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p align=&quot;center&quot;&gt;&lt;span style=&quot; font-size:48pt;&quot;&gt;Input ID&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property>
</widget>
</item>
<item row="8" column="0" colspan="2">
<widget class="QLineEdit" name="inputMail">
<property name="toolTip">
<string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p align=&quot;center&quot;&gt;&lt;span style=&quot; font-size:48pt;&quot;&gt;Input Mail&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property>
</widget>
</item>
<item row="9" column="0" colspan="2">
<widget class="QLabel" name="label_3">
<property name="text">
<string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p align=&quot;center&quot;&gt;&lt;span style=&quot; font-size:28pt;&quot;&gt;Password&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property>
</widget>
</item>
<item row="10" column="0" colspan="2">
<widget class="QLineEdit" name="inputPassword">
<property name="toolTip">
<string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p align=&quot;center&quot;&gt;&lt;span style=&quot; font-size:48pt;&quot;&gt;Input Password&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property>
<property name="whatsThis">
<string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;&lt;br/&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property>
<property name="text">
<string/>
</property>
<property name="echoMode">
<enum>QLineEdit::Password</enum>
</property>
</widget>
</item>
<item row="11" column="0" colspan="2">
<widget class="QPushButton" name="pushButton">
<property name="toolTip">
<string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;&lt;span style=&quot; font-size:72pt;&quot;&gt;Register&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;br/&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property>
<property name="text">
<string>Register</string>
</property>
</widget>
</item>
<item row="7" column="0" colspan="2">
<widget class="QLabel" name="label_2">
<property name="text">
<string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p align=&quot;center&quot;&gt;&lt;span style=&quot; font-size:28pt;&quot;&gt;Mail&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property>
</widget>
</item>
<item row="5" column="0" colspan="2">
<widget class="QLabel" name="label_4">
<property name="text">
<string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p align=&quot;center&quot;&gt;&lt;span style=&quot; font-size:28pt;&quot;&gt;ID&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property>
</widget>
</item>
<item row="12" column="0" colspan="2">
<widget class="QPushButton" name="loginButton">
<property name="text">
<string>Already Registered? Click here to Login!</string>
</property>
</widget>
</item>
<item row="3" column="1">
<widget class="QLabel" name="label_5">
<property name="text">
<string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p align=&quot;center&quot;&gt;&lt;span style=&quot; font-size:28pt;&quot;&gt;Blog Title&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property>
</widget>
</item>
<item row="4" column="0" colspan="2">
<widget class="QLineEdit" name="inputBlogTitle"/>
</item>
<item row="2" column="1">
<widget class="QLineEdit" name="inputBlogID"/>
</item>
<item row="1" column="1">
<widget class="QLabel" name="label_6">
<property name="text">
<string>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p align=&quot;center&quot;&gt;&lt;span style=&quot; font-size:28pt;&quot;&gt;Blog ID&lt;/span&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property>
</widget>
</item>
</layout>
</widget>
<widget class="QMenuBar" name="menubar">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>800</width>
<height>19</height>
</rect>
</property>
<widget class="QMenu" name="menuApp">
<property name="title">
<string>App</string>
</property>
<addaction name="actionExit"/>
<addaction name="actionLogin"/>
</widget>
<addaction name="menuApp"/>
</widget>
<action name="actionExit">
<property name="text">
<string>Exit</string>
</property>
</action>
<action name="actionLogin">
<property name="text">
<string>Login</string>
</property>
</action>
</widget>
<resources/>
<connections/>
</ui>

View File

View File

@ -0,0 +1,76 @@
#ifndef UNIVERSAL_FUNCTIONS_CPP
#define UNIVERSAL_FUNCTIONS_CPP
#include <QJsonObject>
#include <QString>
#include <QJsonDocument>
#include <QFile>
#include <QMessageBox>
#include <QApplication>
QJsonObject readJsonFile(const QString title)
{
QFile file(title);
file.open(QIODevice::ReadWrite); // If the file does not exist we create it
QByteArray bytes = file.readAll();
file.close();
QJsonDocument document = QJsonDocument::fromJson( bytes );
return document.object();
}
void saveJsonFile(QJsonObject &users, const QString name)
{
QFile jsonFile(name);
QJsonDocument document;
document.setObject( users );
QByteArray bytes = document.toJson( QJsonDocument::Indented );
jsonFile.open( QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate );
QTextStream iStream( &jsonFile );
// iStream.setCodec( "utf-8" );
iStream << bytes;
jsonFile.close();
}
void outputMessageBox(const QString messageBoxText)
{
QMessageBox idEmpty;
idEmpty.setText(messageBoxText);
idEmpty.exec();
}
void exit()
{
QApplication::quit();
}
bool stringEmpty(const QString &string, const QString &messageBoxMessage)
{
if(string == "")
{
outputMessageBox(messageBoxMessage);
return true;
}
return false;
}
bool idExists(const QString &id, const QJsonObject &json, const QString &message, const bool &whenMessage)
{
if (json.find(id) != json.end())
{
if (whenMessage) outputMessageBox(message);
return true;
}
if (!whenMessage) outputMessageBox(message);
return false;
}
bool sameString(const QString &stringToCompare, const QString &jsonId, const QJsonObject &json, const QString &message)
{
if(json[jsonId].toString() != stringToCompare)
{
outputMessageBox(message);
return false;
}
return true;
}
#endif

View File

@ -0,0 +1,14 @@
#ifndef UNIVERSALFUNCTIONS_H
#define UNIVERSALFUNCTIONS_H
#include <QJsonObject>
QJsonObject readJsonFile(const QString title);
void saveJsonFile(QJsonObject &users, const QString name);
void outputMessageBox(const QString messageBoxText);
void exit();
bool stringEmpty(const QString &string, const QString &messageBoxMessage);
bool idExists(const QString &id, const QJsonObject &json, const QString &message, const bool &whenMessage);
bool sameString(const QString &stringToCompare, const QString &jsonId, const QJsonObject &json, const QString &message);
#endif // UNIVERSALFUNCTIONS_H

35
EGUI/lab2/.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,35 @@
{
"version": "0.2.0",
"configurations": [
{
// Use IntelliSense to find out which attributes exist for C# debugging
// Use hover for the description of the existing attributes
// For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
"name": ".NET Core Launch (web)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceFolder}/bin/Debug/net6.0/lab2.dll",
"args": [],
"cwd": "${workspaceFolder}",
"stopAtEntry": false,
// Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser
"serverReadyAction": {
"action": "openExternally",
"pattern": "\\bNow listening on:\\s+(https?://\\S+)"
},
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"sourceFileMap": {
"/Views": "${workspaceFolder}/Views"
}
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach"
}
]
}

41
EGUI/lab2/.vscode/tasks.json vendored Normal file
View File

@ -0,0 +1,41 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"command": "dotnet",
"type": "process",
"args": [
"build",
"${workspaceFolder}/lab2.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
"label": "publish",
"command": "dotnet",
"type": "process",
"args": [
"publish",
"${workspaceFolder}/lab2.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
"label": "watch",
"command": "dotnet",
"type": "process",
"args": [
"watch",
"run",
"--project",
"${workspaceFolder}/lab2.csproj"
],
"problemMatcher": "$msCompile"
}
]
}

35
EGUI/lab2/lab2/.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,35 @@
{
"version": "0.2.0",
"configurations": [
{
// Use IntelliSense to find out which attributes exist for C# debugging
// Use hover for the description of the existing attributes
// For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
"name": ".NET Core Launch (web)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceFolder}/bin/Debug/net6.0/lab2.dll",
"args": [],
"cwd": "${workspaceFolder}",
"stopAtEntry": false,
// Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser
"serverReadyAction": {
"action": "openExternally",
"pattern": "\\bNow listening on:\\s+(https?://\\S+)"
},
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"sourceFileMap": {
"/Views": "${workspaceFolder}/Views"
}
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach"
}
]
}

41
EGUI/lab2/lab2/.vscode/tasks.json vendored Normal file
View File

@ -0,0 +1,41 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"command": "dotnet",
"type": "process",
"args": [
"build",
"${workspaceFolder}/lab2.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
"label": "publish",
"command": "dotnet",
"type": "process",
"args": [
"publish",
"${workspaceFolder}/lab2.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
"label": "watch",
"command": "dotnet",
"type": "process",
"args": [
"watch",
"run",
"--project",
"${workspaceFolder}/lab2.csproj"
],
"problemMatcher": "$msCompile"
}
]
}

View File

@ -0,0 +1,28 @@
using Microsoft.AspNetCore.Mvc;
using System.Text.Encodings.Web;
namespace lab2.Controllers
{
public class BlogViewController : Controller
{
//
// GET: /Register/
public IActionResult Index()
{
return View();
}
//
// GET: /Register/RegisterUser/?userid=Rick&email=4&password=test&blogid=blogtest
public IActionResult RegisterUser(string userid, string email, string password, string blogid)
{
ViewData["userid"] = "userid: " + userid;
ViewData["email"] = "email: " + email;
ViewData["password"] = "password: " + password;
ViewData["blogid"] = "blogid: " + blogid;
return View();
}
}
}

View File

@ -0,0 +1,31 @@
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using lab2.Models;
namespace lab2.Controllers;
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
return View();
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}

View File

@ -0,0 +1,28 @@
using Microsoft.AspNetCore.Mvc;
using System.Text.Encodings.Web;
namespace lab2.Controllers
{
public class LoginController : Controller
{
//
// GET: /Login/
public IActionResult Index()
{
return View();
}
//
// GET: /Login/LoginUser/
// https://localhost:{PORT}/Login/LoginUser/?userid=Rick&password=4
public IActionResult LoginUser(string userid, string password)
{
ViewData["userid"] = "userid: " + userid;
ViewData["password"] = "password: " + password;
return View();
}
}
}

View File

@ -0,0 +1,57 @@
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Web;
using Microsoft.AspNetCore.Mvc;
using System.Text.Encodings.Web;
namespace FormEncode.Controllers
{
public class RegisterController : Controller
{
[HttpPost]
[ActionName("Complex")]
public IActionResult PostComplex(string id, string blogid, string blogTitle, string mail, string password)
{
if(id != null && blogid != null && blogTitle != null && mail != null & password != null)
{
// Convert any HTML markup in the status text.
id = HttpUtility.HtmlEncode(id);
blogid = HttpUtility.HtmlEncode(blogid);
blogTitle = HttpUtility.HtmlEncode(blogTitle);
mail = HttpUtility.HtmlEncode(mail);
password = HttpUtility.HtmlEncode(password);
ViewData["userid"] = "userid: " + id;
ViewData["email"] = "email: " + mail;
ViewData["password"] = "password: " + password;
ViewData["blogid"] = "blogid: " + blogid;
ViewData["blogtitle"] = "blogtitle: " + blogTitle;
return View();
}
else return View();
}
//
// GET: /Register/
public IActionResult Index()
{
return View();
}
//
// GET: /Register/RegisterUser/?userid=Rick&email=4&password=test&blogid=blogtest
public IActionResult RegisterUser(string userid, string email, string password, string blogid, string blogtitle)
{
ViewData["userid"] = "userid: " + userid;
ViewData["email"] = "email: " + email;
ViewData["password"] = "password: " + password;
ViewData["blogid"] = "blogid: " + blogid;
ViewData["blogtitle"] = "blogtitle: " + blogtitle;
return View();
}
}
}

View File

@ -0,0 +1,153 @@
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using lab2.Models;
namespace lab2.Controllers
{
public class UserController : Controller
{
private readonly lab2UserContext _context;
public UserController(lab2UserContext context)
{
_context = context;
}
// GET: User
public async Task<IActionResult> Index()
{
return View(await _context.User.ToListAsync());
}
// GET: User/Details/5
public async Task<IActionResult> Details(string id)
{
if (id == null)
{
return NotFound();
}
var user = await _context.User
.FirstOrDefaultAsync(m => m.Id == id);
if (user == null)
{
return NotFound();
}
return View(user);
}
// GET: User/Create
public IActionResult Create()
{
return View();
}
// POST: User/Create
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,email,password")] User user)
{
if (ModelState.IsValid)
{
_context.Add(user);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(user);
}
// GET: User/Edit/5
public async Task<IActionResult> Edit(string id)
{
if (id == null)
{
return NotFound();
}
var user = await _context.User.FindAsync(id);
if (user == null)
{
return NotFound();
}
return View(user);
}
// POST: User/Edit/5
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(string id, [Bind("Id,email,password")] User user)
{
if (id != user.Id)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(user);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!UserExists(user.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(user);
}
// GET: User/Delete/5
public async Task<IActionResult> Delete(string id)
{
if (id == null)
{
return NotFound();
}
var user = await _context.User
.FirstOrDefaultAsync(m => m.Id == id);
if (user == null)
{
return NotFound();
}
return View(user);
}
// POST: User/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(string id)
{
var user = await _context.User.FindAsync(id);
_context.User.Remove(user);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool UserExists(string id)
{
return _context.User.Any(e => e.Id == id);
}
}
}

View File

@ -0,0 +1,17 @@
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using lab2.Models;
public class lab2UserContext : DbContext
{
public lab2UserContext (DbContextOptions<lab2UserContext> options)
: base(options)
{
}
public DbSet<lab2.Models.User> User { get; set; }
}

View File

@ -0,0 +1,16 @@
using System.ComponentModel.DataAnnotations;
namespace lab2.Models
{
public class Blog
{
public string? Id { get; set; }
public string? Title { get; set; }
public string? OwnerId { get; set; }
public BlogEntry[]? Entries {get; set; }
}
}

View File

@ -0,0 +1,12 @@
using System.ComponentModel.DataAnnotations;
namespace lab2.Models
{
public class BlogEntry
{
public string? Title { get; set; }
[DataType(DataType.Date)]
public DateTime datetime { get; set; }
public string? content {get; set; }
}
}

View File

@ -0,0 +1,8 @@
namespace lab2.Models;
public class ErrorViewModel
{
public string? RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}

View File

@ -0,0 +1,11 @@
using System.ComponentModel.DataAnnotations;
namespace lab2.Models
{
public class User
{
public string? Id { get; set; }
public string? email { get; set; }
public string? password { get; set; }
}
}

32
EGUI/lab2/lab2/Program.cs Normal file
View File

@ -0,0 +1,32 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<lab2UserContext>(options =>
options.UseSqlite(builder.Configuration.GetConnectionString("lab2UserContext") ?? throw new InvalidOperationException("Connection string 'lab2UserContext' not found.")));
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();

View File

@ -0,0 +1,28 @@
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:51665",
"sslPort": 44389
}
},
"profiles": {
"lab2": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7161;http://localhost:5226",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

View File

@ -0,0 +1,5 @@
@{
ViewData["Title"] = "Blog View";
}
<h2>Blog View</h2>

View File

@ -0,0 +1,8 @@
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>

View File

@ -0,0 +1,6 @@
@{
ViewData["Title"] = "Privacy Policy";
}
<h1>@ViewData["Title"]</h1>
<p>Use this page to detail your site's privacy policy.</p>

View File

@ -0,0 +1,7 @@
@{
ViewData["Title"] = "Login";
}
<h2>Login</h2>
<p>Hello from our Login Template!</p>

View File

@ -0,0 +1,10 @@
@{
ViewData["Title"] = "Logged User";
}
<h2>Welcome</h2>
<ul>
<li>@ViewData["userid"]</li>
<li>@ViewData["password"]</li>
</ul>

View File

@ -0,0 +1,42 @@
@{
ViewData["Title"] = "Register";
}
<h1>Register</h1>
<form id="form1" method="post" action="Register/PostComplex"
enctype="application/x-www-form-urlencoded">
<div>
<label for="ID">ID</label>
</div>
<div>
<input name="ID" type="ID" />
</div>
<div>
<label for="BlogID">BlogID</label>
</div>
<div>
<input name="BlogID" type="BlogID" />
</div>
<div>
<label for="BlogTitle">Blog Title</label>
</div>
<div>
<input name="BlogTitle" type="BlogTitle" />
</div>
<div>
<label for="Mail">Mail</label>
</div>
<div>
<input name="Mail" type="Mail" />
</div>
<div>
<label for="Password">Password</label>
</div>
<div>
<input name="Password" type="Password" />
</div>
<div>
<input type="submit" value="Register" />
</div>
</form>

View File

@ -0,0 +1,13 @@
@{
ViewData["Title"] = "Register User";
}
<h2>Welcome</h2>
<ul>
<li>@ViewData["userid"]</li>
<li>@ViewData["email"]</li>
<li>@ViewData["password"]</li>
<li>@ViewData["blogid"]</li>
<li>@ViewData["blogtitle"]</li>
</ul>

View File

@ -0,0 +1,25 @@
@model ErrorViewModel
@{
ViewData["Title"] = "Error";
}
<h1 class="text-danger">Error.</h1>
<h2 class="text-danger">An error occurred while processing your request.</h2>
@if (Model.ShowRequestId)
{
<p>
<strong>Request ID:</strong> <code>@Model.RequestId</code>
</p>
}
<h3>Development Mode</h3>
<p>
Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred.
</p>
<p>
<strong>The Development environment shouldn't be enabled for deployed applications.</strong>
It can result in displaying sensitive information from exceptions to end users.
For local debugging, enable the <strong>Development</strong> environment by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>
and restarting the app.
</p>

View File

@ -0,0 +1,52 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - Blog App</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
<link rel="stylesheet" href="~/lab2.styles.css" asp-append-version="true" />
</head>
<body>
<header>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
<div class="container-fluid">
<a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">Blog App</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Register" asp-action="">Register</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Login" asp-action="">Login</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="container">
<main role="main" class="pb-3">
@RenderBody()
</main>
</div>
<footer class="border-top footer text-muted">
<div class="container">
&copy; 2022 - Blog App - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</div>
</footer>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
@await RenderSectionAsync("Scripts", required: false)
</body>
</html>

View File

@ -0,0 +1,48 @@
/* Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification
for details on configuring this project to bundle and minify static web assets. */
a.navbar-brand {
white-space: normal;
text-align: center;
word-break: break-all;
}
a {
color: #0077cc;
}
.btn-primary {
color: #fff;
background-color: #1b6ec2;
border-color: #1861ac;
}
.nav-pills .nav-link.active, .nav-pills .show > .nav-link {
color: #fff;
background-color: #1b6ec2;
border-color: #1861ac;
}
.border-top {
border-top: 1px solid #e5e5e5;
}
.border-bottom {
border-bottom: 1px solid #e5e5e5;
}
.box-shadow {
box-shadow: 0 .25rem .75rem rgba(0, 0, 0, .05);
}
button.accept-policy {
font-size: 1rem;
line-height: inherit;
}
.footer {
position: absolute;
bottom: 0;
width: 100%;
white-space: nowrap;
line-height: 60px;
}

View File

@ -0,0 +1,2 @@
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>

View File

@ -0,0 +1,43 @@
@model lab2.Models.User
@{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>User</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Id" class="control-label"></label>
<input asp-for="Id" class="form-control" />
<span asp-validation-for="Id" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="email" class="control-label"></label>
<input asp-for="email" class="form-control" />
<span asp-validation-for="email" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="password" class="control-label"></label>
<input asp-for="password" class="form-control" />
<span asp-validation-for="password" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

View File

@ -0,0 +1,33 @@
@model lab2.Models.User
@{
ViewData["Title"] = "Delete";
}
<h1>Delete</h1>
<h3>Are you sure you want to delete this?</h3>
<div>
<h4>User</h4>
<hr />
<dl class="row">
<dt class = "col-sm-2">
@Html.DisplayNameFor(model => model.email)
</dt>
<dd class = "col-sm-10">
@Html.DisplayFor(model => model.email)
</dd>
<dt class = "col-sm-2">
@Html.DisplayNameFor(model => model.password)
</dt>
<dd class = "col-sm-10">
@Html.DisplayFor(model => model.password)
</dd>
</dl>
<form asp-action="Delete">
<input type="hidden" asp-for="Id" />
<input type="submit" value="Delete" class="btn btn-danger" /> |
<a asp-action="Index">Back to List</a>
</form>
</div>

View File

@ -0,0 +1,30 @@
@model lab2.Models.User
@{
ViewData["Title"] = "Details";
}
<h1>Details</h1>
<div>
<h4>User</h4>
<hr />
<dl class="row">
<dt class = "col-sm-2">
@Html.DisplayNameFor(model => model.email)
</dt>
<dd class = "col-sm-10">
@Html.DisplayFor(model => model.email)
</dd>
<dt class = "col-sm-2">
@Html.DisplayNameFor(model => model.password)
</dt>
<dd class = "col-sm-10">
@Html.DisplayFor(model => model.password)
</dd>
</dl>
</div>
<div>
<a asp-action="Edit" asp-route-id="@Model?.Id">Edit</a> |
<a asp-action="Index">Back to List</a>
</div>

View File

@ -0,0 +1,39 @@
@model lab2.Models.User
@{
ViewData["Title"] = "Edit";
}
<h1>Edit</h1>
<h4>User</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Edit">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="Id" />
<div class="form-group">
<label asp-for="email" class="control-label"></label>
<input asp-for="email" class="form-control" />
<span asp-validation-for="email" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="password" class="control-label"></label>
<input asp-for="password" class="form-control" />
<span asp-validation-for="password" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Save" class="btn btn-primary" />
</div>
</form>
</div>
</div>
<div>
<a asp-action="Index">Back to List</a>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

View File

@ -0,0 +1,41 @@
@model IEnumerable<lab2.Models.User>
@{
ViewData["Title"] = "Index";
}
<h1>Index</h1>
<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.email)
</th>
<th>
@Html.DisplayNameFor(model => model.password)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.email)
</td>
<td>
@Html.DisplayFor(modelItem => item.password)
</td>
<td>
<a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
<a asp-action="Details" asp-route-id="@item.Id">Details</a> |
<a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
</td>
</tr>
}
</tbody>
</table>

View File

@ -0,0 +1,3 @@
@using lab2
@using lab2.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

View File

@ -0,0 +1,3 @@
@{
Layout = "_Layout";
}

View File

@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

View File

@ -0,0 +1,12 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"lab2UserContext": "Data Source=lab2UserContext-85435385-56ab-4666-ad5b-1892b82e95b9.db"
}
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Some files were not shown because too many files have changed in this diff Show More