Requires that my function is implemented access to the database - database

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

Related

Produce XML from MS SQL, structure issues, namespace prefix:

I'm trying to run SQL for complex XML out of MS SQL Server 2016. I made a huge progress considering that I'm new to XML generation but still can't figure out how to do that nesting portion to make Export/Client structure matter what I tried putting into nested ROOT clause. Not sure if this issue also causing that I'm missing hmis: prefix for most Elements. I need them like on attached picture with Desired output/schema.
Also pasting self containing test Input and working code , I marked with ???? places which I think caused this trouble. Appreciate your hints. Do you think it's will be easy to do with other types FOR XML ? Explicit ???
Best Mario
SQL Version: Microsoft SQL Server 2017 (RTM-CU27)
Updated: added #export table
/* --- test data/table
DROP TABLE IF EXISTS #t;
SELECT * INTO #T FROM ( -- SELECT * FROM #T
SELECT 111 PersonalID, 'Alpha' first_name, 'Brown' last_name, '1/1/2000' birth_date, 'Manager Alpha' CaseManager_PH, 0 Female, '3/2/2022' ExportDate, 'AW3' user_updated UNION
SELECT 222 PersonalID, 'Bobby' , 'Dow' , '2/2/2002', 'Manager2222' , 0 , '3/3/2022' ExportDate, 'BBX3' ) A
SELECT * FROM #T
*/
DECLARE #export TABLE (
ExportDate date , StartDate DATE, EndDate date)
INSERT INTO #export (ExportDate, StartDate, EndDate)
VALUES ('3/22/2022', '1/1/2022', '4/4/2022')
; WITH XMLNAMESPACES ('https://www.hudhdx.info/Resources/Vendors/4_0/HUD_HMIS.xsd' as hmis,
'http://www.w3.org/2001/XMLSchema-instance' AS xsi )
SELECT
10 AS [hmis:SourceID],
111 AS [hmis:Export/ExportID]
,CAST(e.ExportDate AS VARCHAR(10)) AS [hmis:Export/ExportDate] ---<<< Change
,CAST(e.StartDate AS VARCHAR(10)) AS [hmis:Export/ExportPeriod/StartDate]
,CAST(e.EndDate AS VARCHAR(10)) AS [hmis:Export/ExportPeriod/EndDate]
, (
SELECT
ExportDate AS [hmis:Client/#DateCreated], ExportDate AS [hmis:Client/#dateUpdated],
PersonalID AS [hmis:Client/PersonalID],
first_name AS [hmis:Client/first_name],
last_name AS [hmis:Client/last_name],
birth_date AS [hmis:Client/birth_date],
CaseManager_PH AS [hmis:Client/CustomClientElements/CaseManager_PH],
'Unknown' AS [hmis:Client/CustomClientElements/Casemanager_ContactInfo],
user_updated AS [hmis:Client/user_updated]
FROM #t t
-- WHERE 1=1
FOR XML path , ROOT('Export'), TYPE) ---????
FROM #export e
FOR XML PATH('Source'), ROOT('Sources')
Desired output format:
<hmis:Sources xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:hmis="https://www.hudhdx.info/Resources/Vendors/4_0/HUD_HMIS.xsd">
<hmis:Source>
<hmis:SourceID>10</hmis:SourceID>
<hmis:Export>
<ExportID>111</ExportID>
<ExportDate>2022-03-22</ExportDate>
<ExportPeriod>
<StartDate>2022-01-01</StartDate>
<EndDate>2022-04-04</EndDate>
</ExportPeriod>
<hmis:Client DateCreated="3/2/2022" DateUpdated="3/2/2022">
<hmis:PersonalID>111</hmis:PersonalID>
<hmis:first_name>Alpha</hmis:first_name>
<hmis:last_name>Brown</hmis:last_name>
<hmis:birth_date>1/1/2000</hmis:birth_date>
<hmis:CustomClientElements>
<hmis:CaseManager_PH>Manager Alpha</hmis:CaseManager_PH>
<hmis:Casemanager_ContactInfo>Unknown</hmis:Casemanager_ContactInfo>
</hmis:CustomClientElements>
<hmis:user_updated>AW3</hmis:user_updated>
</hmis:Client>
<hmis:Client DateCreated="3/3/2022" DateUpdated="3/3/2022">
<hmis:PersonalID>222</hmis:PersonalID>
<hmis:first_name>Bobby</hmis:first_name>
<hmis:last_name>Dow</hmis:last_name>
<hmis:birth_date>2/2/2002</hmis:birth_date>
<hmis:CustomClientElements>
<hmis:CaseManager_PH>Manager2222</hmis:CaseManager_PH>
<hmis:Casemanager_ContactInfo>Unknown</hmis:Casemanager_ContactInfo>
</hmis:CustomClientElements>
<hmis:user_updated>BBX3</hmis:user_updated>
</hmis:Client>
</hmis:Export>
</hmis:Source>
</hmis:Sources>
Please try the following solution.
The desired output is produced in two steps:
Raw XML via FOR XML PATH('r'), TYPE, ROOT('root').
Fine tuned final XML via XQuery .query() method and FLWOR expression.
Because a minimal reproducible example is not provided, I hope I didn't miss anything.
SQL
-- DDL and sample data population, start
DECLARE #tbl TABLE (
PersonalID INT PRIMARY KEY,
first_name VARCHAR(30),
last_name VARCHAR(30),
birth_date DATE,
CaseManager_PH VARCHAR(30),
Female BIT,
ExportDate DATE,
user_updated VARCHAR(30)
);
INSERT INTO #tbl (
PersonalID,
first_name,
last_name,
birth_date,
CaseManager_PH,
Female,
ExportDate,
user_updated
)
VALUES
(111, 'Alpha', 'Brown', '2000-01-01', 'Manager Alpha', 0, '2022-03-02', 'AW3'),
(222, 'Bobby', 'Dow', '2002-02-02', 'Manager2222', 0 , '2022-03-03', 'BBX3');
DECLARE #export TABLE (ExportDate date , StartDate DATE, EndDate date);
INSERT INTO #export (ExportDate, StartDate, EndDate) VALUES
('2022-03-22', '2022-01-01', '2022-04-04');
-- DDL and sample data population, end
DECLARE #ExportDate date, #StartDate DATE, #EndDate DATE;
SELECT #ExportDate = ExportDate, #StartDate = StartDate, #EndDate = EndDate
FROM #export;
WITH XMLNAMESPACES ('https://www.hudhdx.info/Resources/Vendors/4_0/HUD_HMIS.xsd' as hmis,
'http://www.w3.org/2001/XMLSchema-instance' AS xsi )
SELECT (
SELECT * FROM #tbl
FOR XML PATH('r'), TYPE, ROOT('root'))
.query('<hmis:Sources xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<hmis:Source>
<hmis:SourceID>10</hmis:SourceID>
<hmis:Export>
<ExportID>111</ExportID>
<ExportDate>{sql:variable("#ExportDate")}</ExportDate>
<ExportPeriod>
<StartDate>{sql:variable("#StartDate")}</StartDate>
<EndDate>{sql:variable("#EndDate")}</EndDate>
</ExportPeriod>
{
for $x in /root/r
return <hmis:Client DateCreated="{$x/ExportDate}" DateUpdated="{$x/ExportDate}">
<hmis:PersonalID>{data($x/PersonalID)}</hmis:PersonalID>
<hmis:first_name>{data($x/first_name)}</hmis:first_name>
<hmis:last_name>{data($x/last_name)}</hmis:last_name>
<hmis:birth_date>{data($x/birth_date)}</hmis:birth_date>
<hmis:CustomClientElements>
<hmis:CaseManager_PH>{data($x/CaseManager_PH)}</hmis:CaseManager_PH>
<hmis:Casemanager_ContactInfo>Unknown</hmis:Casemanager_ContactInfo>
</hmis:CustomClientElements>
<hmis:user_updated>{data($x/user_updated)}</hmis:user_updated>
</hmis:Client>
}
</hmis:Export>
</hmis:Source></hmis:Sources>');
Output
<hmis:Sources xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:hmis="https://www.hudhdx.info/Resources/Vendors/4_0/HUD_HMIS.xsd">
<hmis:Source>
<hmis:SourceID>10</hmis:SourceID>
<hmis:Export>
<ExportID>111</ExportID>
<ExportDate>0</ExportDate>
<ExportPeriod>
<StartDate>0</StartDate>
<EndDate>0</EndDate>
</ExportPeriod>
<hmis:Client DateCreated="2022-03-02" DateUpdated="2022-03-02">
<hmis:PersonalID>111</hmis:PersonalID>
<hmis:first_name>Alpha</hmis:first_name>
<hmis:last_name>Brown</hmis:last_name>
<hmis:birth_date>2000-01-01</hmis:birth_date>
<hmis:CustomClientElements>
<hmis:CaseManager_PH>Manager Alpha</hmis:CaseManager_PH>
<hmis:Casemanager_ContactInfo>Unknown</hmis:Casemanager_ContactInfo>
</hmis:CustomClientElements>
<hmis:user_updated>AW3</hmis:user_updated>
</hmis:Client>
<hmis:Client DateCreated="2022-03-03" DateUpdated="2022-03-03">
<hmis:PersonalID>222</hmis:PersonalID>
<hmis:first_name>Bobby</hmis:first_name>
<hmis:last_name>Dow</hmis:last_name>
<hmis:birth_date>2000-01-01</hmis:birth_date>
<hmis:CustomClientElements>
<hmis:CaseManager_PH>Manager2222</hmis:CaseManager_PH>
<hmis:Casemanager_ContactInfo>Unknown</hmis:Casemanager_ContactInfo>
</hmis:CustomClientElements>
<hmis:user_updated>BBX3</hmis:user_updated>
</hmis:Client>
</hmis:Export>
</hmis:Source>
</hmis:Sources>
You mentioned Explicit, so here is solution generated with FOAM. Not that pretty for some but works OK though could have some limitation with super fancy formats and some casese with maxOccurs="0". It also might require some manual tweaking.
I made single table c just as my personal preference, which required me to add top 1 into few levels manually. But also works fine with join
/* --------------------TEST DATA
drop table if exists #tbl
Create table #tbl (
PersonalID INT , first_name VARCHAR(30), last_name VARCHAR(30), birth_date DATE, CaseManager_PH VARCHAR(30), Female BIT, ExportDate DATE, user_updated VARCHAR(30) );
INSERT INTO #tbl
VALUES
(111, 'Alpha', 'Brown', '2000-01-01', 'Manager Alpha', 0, '2022-03-02', 'AW3'),
(222, 'Bobby', 'Dow', '2002-02-02', 'Manager2222', 0 , '2022-03-03', 'BBX3');
create table #export (ExportDate date , StartDate DATE, EndDate date);
INSERT INTO #export (ExportDate, StartDate, EndDate) VALUES
('2022-03-22', '2022-01-01', '2022-04-04');
-- select * from #export
-- select * from #tbl
-- drop table c
Select * into c from (
select c.*, e.StartDate, e.EndDate
, hmis =cast('https://www.hudhdx.info/Resources/Vendors/4_0/HUD_HMIS.xsd' as varchar(255))
, ExportID = '111', SourceID = '10', ContactInfo = 'Unknown'
from #tbl c
join #export e on 1=1
) c
Select * from c
*/
/********************************************
* Output produced by Foam #
* 3/31/2022 12:12:03 PM
*
* digital nothing design
* http://www.digitalnothing.com
********************************************/
SELECT Tag = 1, Parent = NULL,
[hmis:Sources!1!xmlns:hmis] = 'https://www.hudhdx.info/Resources/Vendors/4_0/HUD_HMIS.xsd',
[hmis:Source!2!] = NULL,
[hmis:Source!2!hmis:SourceID!element] = NULL,
[hmis:Export!3!] = NULL,
[hmis:Export!3!ExportID!element] = NULL,
[hmis:Export!3!ExportDate!element] = NULL,
[ExportPeriod!4!] = NULL,
[ExportPeriod!4!StartDate!element] = NULL,
[ExportPeriod!4!EndDate!element] = NULL,
[hmis:Client!5!DateCreated] = NULL,
[hmis:Client!5!DateUpdated] = NULL,
[hmis:Client!5!hmis:PersonalID!element] = NULL,
[hmis:Client!5!hmis:first_name!element] = NULL,
[hmis:Client!5!hmis:last_name!element] = NULL,
[hmis:Client!5!hmis:birth_date!element] = NULL,
[hmis:CustomClientElements!6!] = NULL,
[hmis:CustomClientElements!6!hmis:Casemanager_PH!element] = NULL,
[hmis:CustomClientElements!6!hmis:Casemanager_ContactInfo!element] = NULL,
[hmis:Client!5!hmis:user_updated!element] = NULL
UNION ALL
SELECT top 1 Tag = 2, Parent = 1,
[hmis:Sources!1!xmlns:hmis] = NULL,
[hmis:Source!2!] = NULL,
[hmis:Source!2!hmis:SourceID!element] = c.SourceID,
[hmis:Export!3!] = NULL,
[hmis:Export!3!ExportID!element] = NULL,
[hmis:Export!3!ExportDate!element] = NULL,
[ExportPeriod!4!] = NULL,
[ExportPeriod!4!StartDate!element] = NULL,
[ExportPeriod!4!EndDate!element] = NULL,
[hmis:Client!5!DateCreated] = NULL,
[hmis:Client!5!DateUpdated] = NULL,
[hmis:Client!5!hmis:PersonalID!element] = NULL,
[hmis:Client!5!hmis:first_name!element] = NULL,
[hmis:Client!5!hmis:last_name!element] = NULL,
[hmis:Client!5!hmis:birth_date!element] = NULL,
[hmis:CustomClientElements!6!] = NULL,
[hmis:CustomClientElements!6!hmis:Casemanager_PH!element] = NULL,
[hmis:CustomClientElements!6!hmis:Casemanager_ContactInfo!element] = NULL,
[hmis:Client!5!hmis:user_updated!element] = NULL
from c
UNION ALL
SELECT top 1 Tag = 3, Parent = 2,
[hmis:Sources!1!xmlns:hmis] = NULL,
[hmis:Source!2!] = NULL,
[hmis:Source!2!hmis:SourceID!element] = NULL,
[hmis:Export!3!] = NULL,
[hmis:Export!3!ExportID!element] = c.ExportID,
[hmis:Export!3!ExportDate!element] = c.ExportDate,
[ExportPeriod!4!] = NULL,
[ExportPeriod!4!StartDate!element] = NULL,
[ExportPeriod!4!EndDate!element] = NULL,
[hmis:Client!5!DateCreated] = NULL,
[hmis:Client!5!DateUpdated] = NULL,
[hmis:Client!5!hmis:PersonalID!element] = NULL,
[hmis:Client!5!hmis:first_name!element] = NULL,
[hmis:Client!5!hmis:last_name!element] = NULL,
[hmis:Client!5!hmis:birth_date!element] = NULL,
[hmis:CustomClientElements!6!] = NULL,
[hmis:CustomClientElements!6!hmis:Casemanager_PH!element] = NULL,
[hmis:CustomClientElements!6!hmis:Casemanager_ContactInfo!element] = NULL,
[hmis:Client!5!hmis:user_updated!element] = NULL
from c
UNION ALL
SELECT top 1 Tag = 4, Parent = 3,
[hmis:Sources!1!xmlns:hmis] = NULL,
[hmis:Source!2!] = NULL,
[hmis:Source!2!hmis:SourceID!element] = NULL,
[hmis:Export!3!] = NULL,
[hmis:Export!3!ExportID!element] = NULL,
[hmis:Export!3!ExportDate!element] = NULL,
[ExportPeriod!4!] = NULL,
[ExportPeriod!4!StartDate!element] = c.StartDate,
[ExportPeriod!4!EndDate!element] = c.EndDate,
[hmis:Client!5!DateCreated] = NULL,
[hmis:Client!5!DateUpdated] = NULL,
[hmis:Client!5!hmis:PersonalID!element] = NULL,
[hmis:Client!5!hmis:first_name!element] = NULL,
[hmis:Client!5!hmis:last_name!element] = NULL,
[hmis:Client!5!hmis:birth_date!element] = NULL,
[hmis:CustomClientElements!6!] = NULL,
[hmis:CustomClientElements!6!hmis:Casemanager_PH!element] = NULL,
[hmis:CustomClientElements!6!hmis:Casemanager_ContactInfo!element] = NULL,
[hmis:Client!5!hmis:user_updated!element] = NULL
from c
UNION ALL
SELECT Tag = 5, Parent = 3,
[hmis:Sources!1!xmlns:hmis] = NULL,
[hmis:Source!2!] = NULL,
[hmis:Source!2!hmis:SourceID!element] = NULL,
[hmis:Export!3!] = NULL,
[hmis:Export!3!ExportID!element] = NULL,
[hmis:Export!3!ExportDate!element] = NULL,
[ExportPeriod!4!] = NULL,
[ExportPeriod!4!StartDate!element] = NULL,
[ExportPeriod!4!EndDate!element] = NULL,
[hmis:Client!5!DateCreated] = c.ExportDate,
[hmis:Client!5!DateUpdated] = c.ExportDate,
[hmis:Client!5!hmis:PersonalID!element] = c.PersonalID,
[hmis:Client!5!hmis:first_name!element] = c.first_name,
[hmis:Client!5!hmis:last_name!element] = c.last_name,
[hmis:Client!5!hmis:birth_date!element] = c.birth_date,
[hmis:CustomClientElements!6!] = NULL,
[hmis:CustomClientElements!6!hmis:Casemanager_PH!element] = NULL,
[hmis:CustomClientElements!6!hmis:Casemanager_ContactInfo!element] = NULL,
[hmis:Client!5!hmis:user_updated!element] = c.user_updated
from c
UNION ALL
SELECT Tag = 6, Parent = 5,
[hmis:Sources!1!xmlns:hmis] = NULL,
[hmis:Source!2!] = NULL,
[hmis:Source!2!hmis:SourceID!element] = NULL,
[hmis:Export!3!] = NULL,
[hmis:Export!3!ExportID!element] = NULL,
[hmis:Export!3!ExportDate!element] = NULL,
[ExportPeriod!4!] = NULL,
[ExportPeriod!4!StartDate!element] = NULL,
[ExportPeriod!4!EndDate!element] = NULL,
[hmis:Client!5!DateCreated] = NULL,
[hmis:Client!5!DateUpdated] = NULL,
[hmis:Client!5!hmis:PersonalID!element] = c.PersonalID,
[hmis:Client!5!hmis:first_name!element] = NULL,
[hmis:Client!5!hmis:last_name!element] = NULL,
[hmis:Client!5!hmis:birth_date!element] = NULL,
[hmis:CustomClientElements!6!] = NULL,
[hmis:CustomClientElements!6!hmis:Casemanager_PH!element] = ISNULL(c.Casemanager_PH,''),
[hmis:CustomClientElements!6!hmis:Casemanager_ContactInfo!element] = ISNULL(c.ContactInfo,''),
[hmis:Client!5!hmis:user_updated!element] = NULL
from c
ORDER BY
[hmis:Client!5!hmis:PersonalID!element] ASC,
Tag
FOR XML EXPLICIT
-- sample xml with column names as element values used in FOAM
/*
<hmis:Sources xmlns:hmis="https://www.hudhdx.info/Resources/Vendors/4_0/HUD_HMIS.xsd" >
<hmis:Source>
<hmis:SourceID>c.SourceID</hmis:SourceID>
<hmis:Export>
<ExportID>c.ExportID</ExportID>
<ExportDate>c.ExportDate</ExportDate>
<ExportPeriod>
<StartDate>c.StartDate</StartDate>
<EndDate>c.EndDate</EndDate>
</ExportPeriod>
<hmis:Client DateCreated = "c.ExportDate" DateUpdated="c.ExportDate" >
<hmis:PersonalID>c.PersonalID</hmis:PersonalID>
<hmis:first_name>c.first_name</hmis:first_name>
<hmis:last_name>c.last_name</hmis:last_name>
<hmis:birth_date>c.birth_date</hmis:birth_date>
<hmis:CustomClientElements>
<hmis:Casemanager_PH>c.Casemanager_PH</hmis:Casemanager_PH>
<hmis:Casemanager_ContactInfo>c.ContactInfo</hmis:Casemanager_ContactInfo>
</hmis:CustomClientElements>
<hmis:user_updated>c.user_updated</hmis:user_updated>
</hmis:Client>
</hmis:Export>
</hmis:Source>
</hmis:Sources>
*/

How can we create users with the same email but not the same workflow?

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);

Generate form from database in MVC

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!

Save image to database MVC3

I have a link like this: C:\folder\folder\image.jpg . How can I save image to database in SQL Server?
If it was a HttpPostedFileBase I would knew how to save it, but now I have only a link.
it's a link because I exctracted src tags from tiniMCE editor field .
Thank you.
Have a look at Download and Upload Images from SQL Server via ASP.Net MVC
Code is also available on codeproject.com
Example from msdn social:
table:
CREATE TABLE [dbo].[FileStoreDemo](
[id] [int] NOT NULL,
[name] [nvarchar](100) NOT NULL,
[content] [varbinary](max) NULL,
CONSTRAINT [pk_filestoredemo_id] PRIMARY KEY CLUSTERED ([id] ASC))
code:
string filename = Server.MapPath("/Content/Desert.jpg")
using (fooEntities fe = new fooEntities())
{
FileStoreDemo fsd = fe.FileStoreDemoes.CreateObject();
fsd.name = new FileInfo(filename).Name;
fsd.content = File.ReadAllBytes(filename);
fe.FileStoreDemoes.AddObject(fsd);
fe.SaveChanges();
}
http://social.msdn.microsoft.com/Forums/en/sqlgetstarted/thread/1857938d-b74a-4954-bbde-734dfef08039
[HttpPost]
public ActionResult Create(string fileTitle)
{
try
{
HttpPostedFileBase file = Request.Files[0];
byte[] imageSize = new byte[file.ContentLength];
file.InputStream.Read(imageSize, 0, (int)file.ContentLength);
Image image = new Image()
{
Name = file.FileName.Split('\\').Last(),
Size = file.ContentLength,
Title = fileTitle,
ID = 1,
Image1 = imageSize
};
db.Images.AddObject(image);
db.SaveChanges();
return RedirectToAction("Detail");
}
catch(Exception e)
{
ModelState.AddModelError("uploadError", e);
}
return View();
}

phonegap database error code 5 - non an error

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

Resources