How to initialize sqlite db when using only angular.js and cordova without ionic?
Below is the sequence of existing app initialization.
$(function() {
new init();
});
var init = function() {
// Check platform - web browser, iOS, android
if (navigator.userAgent.match(/(iOS|iPad|iPhone|Android)/)) {
document.addEventListener("deviceready", onDeviceReady, false);
} else {
initializeApp('browser');
}
// Device Ready event for cordova
function onDeviceReady() {
initializeApp('device');
}
// Bootstrapping Angular manually.
function initializeApp(platform) {
angular.element(document).ready(function() {
angular.bootstrap(document, ['myApp']);
});
}
}
// Angular Module and configurations
var myApp = angular.module('myApp', ['ngAnimate','ui.router', 'myApp.constants', 'myApp.helper','myApp.directives', 'myApp.utils', 'myApp.services','ngSanitize', 'ui.bootstrap', 'myApp.filter','chart.js']);
Yes you can use .run method for creating db. here i attach my code for sqlite for web and cordova also so you can sqlite db in browser when you use ionic serve
var db = null;
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services','ngCordova','timer','ionic-datepicker','ionic-timepicker'])
.run(function($ionicPlatform,$cordovaSQLite,$ionicPopup)
{
$ionicPlatform.ready(function()
{
if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard)
{
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar)
{
StatusBar.styleLightContent();
}
if(window.cordova)
{
// App syntax
db = $cordovaSQLite.openDB("myapp.db");
}
else
{
// Ionic serve syntax
db = window.openDatabase("myapp.db", "1.0", "My app", -1);
}
$cordovaSQLite.execute(db,"CREATE TABLE IF NOT EXISTS Users ( UserId INTEGER NOT NULL UNIQUE PRIMARY KEY, CloudId INTEGER, Email TEXT NOT NULL UNIQUE, IsEmailVerified TEXT DEFAULT 'N' NOT NULL, FirstName TEXT NOT NULL, LastName TEXT NOT NULL, UserLanguage TEXT NOT NULL DEFAULT English, IsAutoSyncOn BOOL NOT NULL DEFAULT 1, DateUpdated TIMESTAMP DEFAULT CURRENT_TIMESTAMP, DateAdded TIMESTAMP DEFAULT CURRENT_TIMESTAMP, DateDeleted TIMESTAMP)");
$cordovaSQLite.execute(db,"CREATE TABLE IF NOT EXISTS Photos( PhotoId INTEGER NOT NULL UNIQUE PRIMARY KEY, Source TEXT 'Standard' NOT NULL, Category TEXT, ThumbnailURL TEXT NOT NULL, PhotoURL TEXT NOT NULL, DateAdded TIMESTAMP DEFAULT CURRENT_TIMESTAMP, DateUpdated TIMESTAMP DEFAULT CURRENT_TIMESTAMP, DateDeleted TIMESTAMP)");
$cordovaSQLite.execute(db,"CREATE TABLE IF NOT EXISTS Devices( DeviceId INTEGER NOT NULL UNIQUE PRIMARY KEY, UserId INTEGER NOT NULL, DbVersion INTEGER NOT NULL DEFAULT 1, DateLastLogin TIMESTAMP DEFAULT CURRENT_TIMESTAMP, NbrTimesSinceLastUpgradeNag INTEGER NOT NULL DEFAULT 1, DateLastSync TIMESTAMP, DateSyncServiceExpires TIMESTAMP, DateLastReviewRequest TIMESTAMPDEFAULT CURRENT_TIMESTAMP, NbrLogins INTEGER NOT NULL DEFAULT 1, DeviceName TEXT NOT NULL DEFAULT iPhone, DateUpdated TIMESTAMP DEFAULT CURRENT_TIMESTAMP, DateAdded TIMESTAMP DEFAULT CURRENT_TIMESTAMP)");
$cordovaSQLite.execute(db,"CREATE TABLE IF NOT EXISTS Events( EventId INTEGER NOT NULL UNIQUE PRIMARY KEY, CloudId INTEGER,UserId INTEGER NOT NULL, EventName TEXT NOT NULL, DateEvent TIMESTAMP, Category TEXT, ReminderIntervalNbr TEXT, ReminderIntervalUnits TEXT, RepeatInterval TEXT 'No Repeat' NOT NULL, PhotoId INTEGER, DateUpdated TIMESTAMP DEFAULT CURRENT_TIMESTAMP, DateAdded TIMESTAMP DEFAULT CURRENT_TIMESTAMP, DateDeleted TIMESTAMP)");
});
})
Related
I want to make it possible to create several users, even with the same email address as long as they do not have the same "IdWorkflow" number.
But obviously it doesn't work... result.Succeeded is always false. & all I have is that message : "User name 'test#test.com' is already taken."
What can I do...?
Register.cshtml.cs
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = Input.Email, Email = Input.Email, IdWorkflow = Input.IdWorkflow };
var result = await _userManager.CreateAsync(user, Input.Password);
if (result.Succeeded)
{
_logger.LogInformation("User created a new account with password.");
var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
var callbackUrl = Url.Page(
"/Account/ConfirmEmail",
pageHandler: null,
values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
protocol: Request.Scheme);
await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
$"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");
if (_userManager.Options.SignIn.RequireConfirmedAccount)
{
return RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl });
}
else
{
await _signInManager.SignInAsync(user, isPersistent: false);
return LocalRedirect(returnUrl);
}
}
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
AspNetUsers.sql
CREATE TABLE [dbo].[AspNetUsers] (
[Id] NVARCHAR (450) NOT NULL,
[UserName] NVARCHAR (256) NULL,
[NormalizedUserName] NVARCHAR (256) NULL,
[Email] NVARCHAR (256) NULL,
[NormalizedEmail] NVARCHAR (256) NULL,
[EmailConfirmed] BIT NOT NULL,
[PasswordHash] NVARCHAR (MAX) NULL,
[SecurityStamp] NVARCHAR (MAX) NULL,
[ConcurrencyStamp] NVARCHAR (MAX) NULL,
[PhoneNumber] NVARCHAR (MAX) NULL,
[PhoneNumberConfirmed] BIT NOT NULL,
[TwoFactorEnabled] BIT NOT NULL,
[LockoutEnd] DATETIMEOFFSET (7) NULL,
[LockoutEnabled] BIT NOT NULL,
[AccessFailedCount] INT NOT NULL,
[DateCreate] DATETIME2 (7) DEFAULT ('0001-01-01T00:00:00.0000000') NOT NULL,
[DateUpdate] DATETIME2 (7) DEFAULT ('0001-01-01T00:00:00.0000000') NOT NULL,
[IdWorkflow] NVARCHAR (450) NULL,
CONSTRAINT [PK_AspNetUsers] PRIMARY KEY CLUSTERED ([Id] ASC)
);
GO
CREATE UNIQUE NONCLUSTERED INDEX [UserNameIndex]
ON [dbo].[AspNetUsers]([NormalizedUserName] ASC, [IdWorkflow] ASC) WHERE ([NormalizedUserName] IS NOT NULL);
Requires that my function is implemented access to the databaseand certain operations were carried out.
Such as:
1) Check or read the message.
2) Checking and issuing all communications between users by date.
3) Find the latest posts from all users.
But I though there is material in the tutorial I could not figure out how to do. All I could show you. Therefore, I want to ask you to see my code and see what's up there and help me out. You do not need to completely write code. Just if it's not hard for you to sink your sleeves and calmly give examples let me write these three functions on LINQ and EntityFramework
MY CODE:
public bool CheckIfUnreadMessagesArePresent(int userId)
{
IList<MessageInfo> messageInfo = new List<MessageInfo>();
MessageInfo messageIn = new MessageInfo();
var sql = #"SELECT * FROM MessageInfo
WHERE wasRead = 0 AND Id = #userId ORDER BY date DESC";
var meassage = dataBaseContext.Database.SqlQuery<MessageInfo>(sql, new { userId = messageIn.Id });
return messageInfo.Any(messageIn.WasRead == true);
}
public IList<UserInfo> FetchMessagesFromConversation(int userID1, int userID2)
{
IList<UserInfo> messageInfo = new List<UserInfo>();
MessageInfo messageIn = new MessageInfo();
var sql = #"SELECT * FROM MessageInfo
WHERE userID1 = 1 AND userID2 = 3 OR userID1 = 3 AND userID2 = 1 order by date DESC";
var meassage = dataBaseContext.Database.SqlQuery<MessageInfo>(sql, new { userID1 = messageIn.SenderId,userID2 = messageIn.ReceiverId});
messageInfo.Insert(message);
return messageInfo;
}
public IList<MessageInfo> FetchLastMessageFromEachConversation((int userID))
{
IList<UserInfo> messageInfo = new List<UserInfo>();
MessageInfo messageIn = new MessageInfo();
var sql = #"SELECT * FROM MessageInfo
WHERE date IN (#SELECT max(date)
FROM MessageInfo WHRERE date IN (
SELECT max(date)
FROM MessageInfo
GROUP BY messageIn.ID, messageIn.ReceiverId
ORDER BY date DESC, messageIn.ID, messageIn.ReceiverId)
GROUP BY if (messageIn.ID < messageIn.ReceiverId,
concat(messageIn.ID, " - ", messageIn.ReceiverId), concat(messageIn.ReceiverId, " - ", messageIn.ID)))";
var meassage = dataBaseContext.Database.SqlQuery<MessageInfo>(sql, new { userID1 = messageIn.SenderId, userID2 = messageIn.ReceiverId });
return messageInfo;
}
My DataBase
CREATE TABLE [dbo].[UserInfo](
[Id] [int] IDENTITY(1,1) PRIMARY KEY NOT NULL,
[Login] [varchar](50) NOT NULL,
[Password] [varchar](50) NOT NULL,
[FirstName] [nchar](10) NOT NULL,
[LastName] [nchar](10) NOT NULL,
[Email] [varchar](50) NOT NULL,
[RegistrationDate] [datetime] NOT NULL,
)
GO
CREATE TABLE [dbo].[Messages](
[Id] [int] IDENTITY(1,1) PRIMARY KEY NOT NULL,
[SenderId] [int] NOT NULL,
[ReceiverId] [int] NOT NULL,
[Message] [varchar](500) NOT NULL,
[date] [datetime] NOT NULL,
[WasRead][bit] NOT NULL
CONSTRAINT FK_UserInfoSender FOREIGN KEY (SenderId)
REFERENCES [UserInfo](Id),
CONSTRAINT FK_UserInfoReceiver FOREIGN KEY (ReceiverId)
REFERENCES [UserInfo](Id)
)
GO
I am trying to generate form from my database.
CREATE TABLE [dbo].[FieldsMaster](
[FieldId] [int] IDENTITY(1,1) NOT NULL,
[FieldControlName] [varchar](50) NULL,
[FieldDataType] [varchar](20) NULL,
[FieldControlType] [varchar](30) NULL,
[DisplayLabel] [varchar](200) NULL,
[FieldSize] [int] NULL,
[FieldRegularExpression] [varchar](200) NULL,
[FieldOptions] [varchar](500) NULL,
[OptionalQuery] [varchar](200) NULL,
[REMessage] [varchar](150) NULL,
[FieldRequired] [bit] NULL,
[FRMessage] [varchar](150) NULL
)
Generate some data for the table
insert into FieldsMaster (FieldControlName,FieldDataType,FieldControlType,DisplayLabel,FieldSize,FieldRegularExpression,
FieldOptions,OptionalQuery,REMessage,FieldRequired,FRMessage,IsActive)
values
('txtOtherInfo','varchar','TextArea','Other Information',400,NULL,
NULL,NULL,NULL,0,NULL)
insert into FieldsMaster (FieldControlName,FieldDataType,FieldControlType,DisplayLabel,FieldSize,FieldRegularExpression,
FieldOptions,OptionalQuery,REMessage,FieldRequired,FRMessage,IsActive)
values
('txtTitle','varchar','TextBox','Title',100,NUll,
NULL,NULL,NULL,1,'Please enter title')
Now this form with it fields is stored in my sql db. I want to generate a form in mvc. How the model should be formed/ how to generate form in view?
I am really confused here. Your help is really appreciated. Thanks
To have more idea, below form should be displayed based on the fields in FieldsMaster
Other Information(as label) : TextArea (With Id as txtOtherInfo)
Title (as Label) : TextBox (With Id as txtTitle)
If you want to add form directly from database, you can do.
First you need to do into model an Enum like these (for email):
public int EmailTemplateId { get; set; }
public int Type { get; set; }
public string Name { get; set; }
public enum Emailtype
{
Base = 0,
Recovery = 1,
NewAccount = 2,
ChangePassword = 3,
BlockAccount = 4,
UnlockAccount = 5,
ForgetPassword = 6
}
So each one of thee represent a different template, and in your template view you have something like
<body>
//some code of your template
{-container-}
</body>
As you can see {-container-} is the property you change for each template. so you made new containers that you´be insert into sql like
<tr>
<td>Hi {name}. Your password is {password}</td>
</tr>
You don´t need tag here because you have it into your first template and this code
And in controller:
public void NewAccount(string name, string email,string password, string user)
{
var from = model.From;
var loginUrl = model.LoginUrl;
const string title = "New Register - Stackoverflow";
EmailsService sendEmail = new EmailsService
{
Subject = title,
To = email,
From = from
};
}
//There is our first template (Base template)
var templateBase = Get(Emailtype.Base);
//This one is template who changes (container)
var templateText = Get(Emailtype.NewAccount);
//Here you replace Name property of class for your container code
var body = templateBase.Name.Replace("{-container-}", templateText.Name);
sendEmail.EmailBody = body.Replace("{Name}", name)
.Replace("{Title}", title)
.Replace("{User}", user)
.Replace("{Password}", password)
.Replace("{Link}", loginUrl);
sendEmail.Send();
}
Finally in your sql you can insert code of your container... it show like that:
EmailTemplateId=1
Type= 1 //(Recovery ones)
Name= <tr> <td>Hi {name}. Your password is {password}</td> </tr>
Hope it helps!
I am working on a phonegap application and have the following code:
db = window.openDatabase("AjansDB", "1.0", "Ajans app DB", 2*1024*1024);
//creation
db.transaction(function (tx) {
var sql='CREATE TABLE IF NOT EXISTS USER_DATA (user_id INTEGER PRIMARY KEY, user_name VARCHAR(20))'
tx.executeSql(sql);
});
//insert
var sql="INSERT INTO USER_DATA (user_id,user_name) VALUES (?,?)";
tx.executeSql(sql,[1,"admin"], successCB, errorCB);
Now here is the problem: every time I select from the table I can retrieve the id but not the name ! The id would return "1" while the name would return "undefined"
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM USER_DATA', [], function (tx, results) {
alert(results.rows.item(0).user_name);
});
});
What is going on wrong?
ps: I am not sure if this is gonna make any difference but I am using ionic and angular.js
I was so focused on sql errors that I missed a javascript syntax error. here it's:
var sql='CREATE TABLE IF NOT EXISTS USER_DATA (user_id INTEGER PRIMARY KEY, user_name VARCHAR(20))'
I missed a ";" .. a semicolon.
I am using phonegap to access the phone database. But my create process calls everytime the error routine with error code: 5 and message: non an error?
Isn't it possible to execute multiple sql statements in one transaction?
SQLite Expert couldnt find an syntax error...
createDB: function(error, success) {
if(typeof error != 'function') error = this.errorDB;
if(typeof success != 'function') success = this.successDB;
sql = "DROP TABLE IF EXISTS `boiler`; "
+"CREATE TABLE IF NOT EXISTS `boiler` ( "
+" `id` int NOT NULL, `object` int NOT NULL, `number` varchar(100) NOT NULL, "
+" `volume` double DEFAULT NULL, `brand` varchar(100) DEFAULT NULL, `year` year(4) DEFAULT NULL, "
+" `price_before` float NOT NULL DEFAULT '0', `price_after` float NOT NULL DEFAULT '0', `description` TEXT DEFAULT NULL, "
+" `img1` varchar(200) DEFAULT NULL, `img2` varchar(200) DEFAULT NULL, `img3` varchar(200) DEFAULT NULL, "
+" `img4` varchar(200) DEFAULT NULL, `img5` varchar(200) DEFAULT NULL, `img6` varchar(200) DEFAULT NULL, "
+" `img7` varchar(200) DEFAULT NULL, `img8` varchar(200) DEFAULT NULL, `img9` varchar(200) DEFAULT NULL, "
+"PRIMARY KEY (`id`)); "
+"DROP TABLE IF EXISTS `counter`; "
+"CREATE TABLE IF NOT EXISTS `counter` ( "
+" `number` varchar(100) NOT NULL, `object` int NOT NULL, `type` tinyint NOT NULL DEFAULT '0', "
+" `value` double DEFAULT NULL, `access` varchar(100) DEFAULT NULL, "
+"PRIMARY KEY (`number`)); "
+"DROP TABLE IF EXISTS `link`; "
+"CREATE TABLE IF NOT EXISTS `link` ( "
+" `id` int NOT NULL, `boiler` int NOT NULL, `name` varchar(100) DEFAULT NULL, "
+" `units` tinyint DEFAULT NULL, `price` float NOT NULL DEFAULT '0', "
+"PRIMARY KEY (`id`)); "
+"DROP TABLE IF EXISTS `manager`; "
+"CREATE TABLE IF NOT EXISTS `manager` ( "
+" `id` int NOT NULL, `company` varchar(100) DEFAULT NULL, `name` varchar(100) NOT NULL, "
+" `phone` varchar(15) DEFAULT NULL, "
+"PRIMARY KEY (`id`)); "
+"DROP TABLE IF EXISTS `object`; "
+"CREATE TABLE IF NOT EXISTS `object` ( "
+" `id` int NOT NULL, `state` tinyint NOT NULL DEFAULT '0', `user` varchar(50) DEFAULT NULL, "
+" `date` char(15) DEFAULT NULL, `street` varchar(100) DEFAULT NULL, `number` varchar(16) DEFAULT NULL, "
+" `zip` char(5) DEFAULT NULL, `city` varchar(100) DEFAULT NULL, `manager` int NOT NULL DEFAULT '0', "
+" `units` int NOT NULL DEFAULT '0', "
+"PRIMARY KEY (`id`));";
console.log(sql);
this.DB.transaction(function (tx) { tx.executeSql(sql); }, error, success);
},
don't know the error code: 5 but you can execute the multiple sql statements
// Wait for PhoneGap to load
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
function onDeviceReady() {
var db = window.openDatabase("Database", "1.0", "PhoneGap Demo", 200000);
db.transaction(populateDB, errorCB, successCB);
}
// Populate the database
function populateDB(tx) {
tx.executeSql('DROP TABLE IF EXISTS DEMO');
tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id unique, data)');
tx.executeSql('INSERT INTO DEMO (id, data) VALUES (1, "First row")');
tx.executeSql('INSERT INTO DEMO (id, data) VALUES (2, "Second row")');
//here you can do multiple sql statements.
}
// Transaction error callback
function errorCB(err) {
alert("Error processing SQL: "+err);
}
// Transaction success callback
function successCB() {
alert("success!");
}
link here
Please Check Your Database From File Explorer
there is problem only in the creation of table like you are entering four values but in your table there are only three columns so this error occours
tx.executeSql("CREATE TABLE IF NOT EXISTS quotes(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,name,flag INTEGER,address,description,phone_number,date INTEGER,quote_number,job,images)");
Error is due to if you are assigning directly integer value instead of var type value
like for flar i am using 1 or 0
but now i store this value in var type