Retrieving data through LINQ to SQL - asp.net

I got a weird problem here like I got a site that users can post comments on a friend profile page.Everytime a user post a comment my application sends e-mail to that page owner, you know to inform for a new posted comment on his/her profile page.The problem is I want to stop the application from sending email if that user has just recently posted a comment say like 5 hours ago/earlier.Here is the function I use that would try to check it:
Public Function CheckForNewPost(ByVal arg As String) As Boolean
Dim x As Integer = 0
Using dc As New WhatEverDataContext()
Dim newcomment = From mytable In dc.PostTable _
Where mytable.PostingUser.ToLower() = User.Identity.Name.ToLower() And mytable.PageOwner.ToLower() = arg.ToLower() And mytable.PostedDate.AddHours(5) >= DateTime.Now _
Select mytable
For Each comment In newcomment
x = x + 1
Next
If x > 0 Then
'user has posted a comment recently
Return True
Else
Return False
End If
End Using
End Function
Then I use it like this:
Protected Sub Repeater1_ItemInserted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewInsertedEventArgs) Handles Repeater1.ItemInserted
'send our mail
Dim PageOwner As String = Request.QueryString.Get("PageOwnerName")
If CheckForNewPost(PageOwner) = False Then
SendEMail(PageOwner)
End If
End Sub
But still the app still sending the mail even the user just posted 5 hours earlier.
What do you think I'm doing here?

I think it will be clearer if you write your condition as
mytable.PostedDate <= DateTime.Now.AddHours(-5)
as the right hand side now reads as "Five Hours Ago."
So the entire condition now reads as My posted date is earlier than (or equal to) five hours ago.

You should be checking to see if mytable.PostedDate.AddHours(5) <= DateTime.Now. I think you just got it backwards.
mytable.PostedDate.AddHours(5) <= DateTime.Now

Related

How can I store the data in memory and use by the other Button click event to display the data?

Here is the code, but the datatable is NULL in ButtonExport click event, how can i pass the DataTable to Sub ButtonExport_Click ? I dont want to store in Session as the data is too big
Here is the class clsGlobalVarriable
Public Class clsGlobalVariable
Private _gdt As DataTable
Public Property globalDataTable As DataTable
Get
Return _gdt
End Get
Set(ByVal value As DataTable)
_gdt = value
End Set
End Property
End Class
Here is the From frmTest code:
Public Class frmTest
Inherits System.Web.UI.Page
Private gdt As New clsGlobalVariable
Protected Sub ButtonInactivePC_Click(sender As Object, e As EventArgs) Handles ButtonInactivePC.Click
Try
Dim func As New clsFunction
Dim command As String = "Get-ADComputer -Filter { OperatingSystem -NotLike '*Windows Server*'} -Property * | select Name, CanonicalName, operatingSystem, LastLogonDate, Description, whenChanged | Where {($_.LastLogonDate -lt (Get-Date).AddDays(-90)) -and ($_.LastLogonDate -ne $NULL)}"
Dim arr As New ArrayList
arr.Add("Name")
arr.Add("CanonicalName")
arr.Add("operatingSystem")
arr.Add("LastLogonDate")
arr.Add("whenChanged")
arr.Add("Description")
gdt.globalDataTable = func.PSObjectToDataTable(command, arr)
Me.GridView1.DataSource = gdt.globalDataTable
Me.GridView1.DataBind()
Catch ex As Exception
Me.LabelDebug.Text = "Button Click" + ex.Message
End Try
End Sub
Protected Sub ButtonExport_Click(sender As Object, e As EventArgs) Handles ButtonExport.Click
Dim func As New clsFunction
Dim dt As New DataTable
dt = (DirectCast(Me.GridView1.DataSource, DataTable))
Me.LabelDebug.Text = "Global Data Table Count = " & dt.Rows.Count
End Sub
When working with webpages that show data to the user, and the user takes some action on that data you either need to store the data somewhere in their computer, your computer (the server) or rely on the fact that it's still stored in the computer you got it from. As a process you have undertaken:
You generate a grid from querying AD
You send the grid to the customer's computer - so it's stored there as a visual representation (and maybe also ViewState)
It's still stored in AD, where you got it
You could also store it locally on the server somehow - Session, DB, text file, whatever
Decide on which of these to use when the user clicks Export:
Dig it out of the viewstate or other data that was sent to the user - for this you'll have to code things up so it comes back from the user
Get it out of AD again - simple to do; you did it once and sent it to the user in HTML. Getting it again and sending it to the user again this time as a CSV isn't really any different from the first time you did it
Restore it from wherever you kept it on the server
Choose the first if your user is going to modify the data or choose to export only some of it - the data he sends back to you should indicate which bits he wants exporting.
Choose the second option if you want an easy life, and it's just a straight export, no editing or subset of data. Write one method that gets the data out of AD and then use it in either place, one to form HTML/fill a grid, in the other to send a file to the user. Don't get hung up on "well I already got this data once, it's a waste to get it again" - no-one writes a Login Page and thinks "i'll only ever look up a user from the DB once, then get the server to remember the login data forever more and use it next time there is a login request" - they store the data in the db, and look it up every time there is a login. DBs store data and perform the same queries over and over again. This is no different
You probably wouldn't choose the third option, for reasons already mentioned
I decided to use alternative for the Excel Export, i am not going to pass the DataTable, instead i pass the GridView to the Export to Excel function
Add the following sub right after Page_load, this is to avoid the GridView error
Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
End Sub
Here is the Code:
Public Sub ExportFromGridview(ByVal gv As GridView, ByVal response As HttpResponse
response.Clear()
response.Write("<meta http-equiv=Content-Type content=text/html;charset=utf-8>")
response.AddHeader("content-disposition", "attachment;filename=" & Now & ".xls")
response.ContentType = "application/vnd.xls"
Dim stringWrite As System.IO.StringWriter = New System.IO.StringWriter()
Dim htmlWrite As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(stringWrite)
gv.RenderControl(htmlWrite)
response.Write(stringWrite.ToString())
response.End()
End Sub

Passing cart value between one webform to another in VB.net asp.net

I am trying to build a online store using vb.net 2015 where i need to carry the cart value through my webforms. Currently my cart code is:
Private Sub BtnCal_Click(sender As Object, e As EventArgs) Handles BtnCal.Click
Const mango As Integer = 50
Const apple As Integer = 120
Const beans As Integer = 80
Dim sum As Integer
If Chk_Mango.Checked = True Then
sum += mango
End If
If Chk_apple.Checked = True Then
sum += apple
End If
If Chk_Beans.Checked = True Then
sum += beans
End If
txt_total.Text = sum.ToString(ā€œcā€)
Response.Redirect("cart.aspx", sum)
End Sub
I want to carry the value txt_total.text holds to my next webform, i assume i am sending the cart value correctly by using response.redirect along with sum as parameter. My question is how do i carry forward this value using request code in next webform.
The easiest way is to save the data as a session object. You can retrieve it on your next page.
Session("Total") = txt_total.Text
Dim total As String = Session("Total")
You do not need to declare or create session objects, just assign a key and a value, and the data is stored in the session until the session is timed out or ended.
From current page, before redirect
Session("sum") = txt_total.Text
On second page's page load event.
Dim sum As double = (double)Session("sum")

Evaluating whether a page is the result of a referral from a particular page

I have an Edit Profile page which allows users to change their information - currently it only allows users who have a record in the table 'userprofiles' to edit their information. I want newly registered users to be able to edit their profiles as well.
At the minute, I am using the ASP.NET membership system with the appropriate asp.net_ tables in an Access database to store user credentials. The 'userprofiles' table is a separate table which has more personal information in it. There is no link between the two tables
Here is my code behind:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsCrossPagePostBack Then
SeparateNewUserFunction()
Return
End If
If Not IsPostBack Then
DisplayData()
SaveConfirmation.Visible = False
End If
End Sub
And here is my DisplayData() function just if anyone was interested as to what it does:
Protected Sub DisplayData()
Dim conn As OleDbConnection = New OleDbConnection(ConfigurationManager.ConnectionStrings("BookMeetConnString").ConnectionString)
Dim sql = "SELECT * FROM userprofiles WHERE TravellerName=#f1"
Dim cmd = New OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#f1", User.Identity.Name)
conn.Open()
Dim profileDr = cmd.ExecuteReader()
profileDr.Read()
Dim newEmailAddress = ""
Dim newDescription = ""
If Not IsDBNull(profileDr("EmailAddress")) Then newEmailAddress = profileDr.Item("EmailAddress")
If Not IsDBNull(profileDr("Description")) Then newDescription = profileDr.Item("Description")
If Not IsDBNull(profileDr("AvatarURL")) Then ProfilePic.ImageUrl = profileDr.Item("AvatarURL")
description.Text = newDescription
email.Text = newEmailAddress
conn.Close()
End Sub
Rather than checking if a record exists in the 'userprofiles' table that matches the User.Identity.Name of the current user, I thought it would be easier just to evaluate whether or not the user had just been redirected from the Register.aspx page. (If this evaluation is true, then as you can see above, a separate "New User" function will be called).
That is my logic, but I have no clue if VB.NET has a "referrer" or "isReferred" expression? (at the minute as you can see I thought isCrossPagePostback might be the right thing but no luck!)
Any ideas?
You need to check whether or not a record exists and base your logic on that. That is the only right way to do it. As in:
What if you introduce a new page to handle registrations? This logic breaks.
What if you one day you retire and the next guy decides to rename the Register.aspx page? This logic breaks.
What if user hits back button and clicks the Register button again? This logic may break.
You should also consider a foreign key and unique constraint on that table, as well as using UserId instead of TravellerName. TravellerName can change, UserId will not.
... and yes you can the referring page by using HttpRequest.ServerVariables, which gets you a list of IIS Server Variables.

asp.net list of users by profile property

I have created some profile properties for when a new user is added to our system.
One property is called 'Client' and links this user to a particular client and stores a client id.
I am trying to create a page that shows a list of users for each client on the system such as:
Client 1
User 1
User 2
User 3
Client 2
User 4
User 5
User 6
Client 3
User 7
User 8
User 9
Is there a way to get a list of users that match a particular profile property?
Thanks for any help. J.
The code below is an old VB.Net method I wrote to filter users based on a profile value. It could be slightly modified to accomplish your task.
Function FindUsers(ByVal prop As String, ByVal val As String) As List(Of ProfileCommon)
' Use a generic list of people
Dim peeps As New List(Of ProfileCommon)()
ViewState("prop") = prop
ViewState("val") = val
' Get all profile objects
Dim profiles As ProfileInfoCollection = ProfileManager.GetAllProfiles(ProfileAuthenticationOption.All)
' Go through the profiles
For Each info As ProfileInfo In profiles
' We need to turn a ProfileInfo into a ProfileCommon
' to access the properties to do the search
Dim userProfile As ProfileCommon = ProfileCommon.Create(info.UserName)
If Roles.IsUserInRole(info.UserName, "Members Subscribers") Then
' If the birthday matches
If val <> "" Then
If prop <> "" AndAlso Left(userProfile.Item(prop), val.Length) = val Then
' Add them to our list
peeps.Add(userProfile)
End If
Else
peeps.Add(userProfile)
End If
End If
Next
If peeps.Count > 0 Then ShowUserDetails(peeps(0).UserName)
Return peeps
End Function
Found what i was looking for, ended up using this:
http://pretzelsteelersfan.blogspot.com/2007/03/get-aspnet-profile-properties-from-sql.html
Thanks for any help though.

Online Test using ASP.NET / Linq

Working on a Online Test.
I have 3 tables
Questions
Subject
Topic
I have made a stored procedure which returns 25 random records. I want to store it in-memory and then display 1 question at a time with AJAX. I don't want to hit database 25 times as there are many users, I tried and store the result in viewstate but then I am not able to cast it back. if I use
Dim qus = from viewstate("questions")
it works, but it doesn't work when I retrieve 1 record at a time.
Code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
ViewState.Add("QuestionNo", 0)
Dim qus = From q In PML.PM_SelectRandomQuestionFM Select q
viewstate.add("questions",qus)
LoadQuestion(0)
End If
End Sub
Private Sub LoadQuestion(ByVal i As Integer)
Dim QuestionNo As Integer = CType(ViewState("QuestionNo"), Integer) + 1
Try
If QuestionNo <= 25 Then
Dim qus = viewstate("questions")
Me._subjectTopic.Text = String.Format("<b>Subject:</b> {0} -- <b>Topic:</b> {1}", qus(i).subjectName, qus(i).TopicName)
Me._question.Text = " " & qus(i).Question
Me._answer1.Text = " " & qus(i).Answer1
Me._answer2.Text = " " & qus(i).Answer2
Me._answer3.Text = " " & qus(i).Answer3
Me._answer4.Text = " " & qus(i).Answer4
Me._questionNo.Text = String.Format("Question No. {0} / 25", QuestionNo)
ViewState.Add("QuestionNo", QuestionNo)
Else
Server.Transfer("freeMemberResult.aspx")
End If
Catch ex As Exception
Throw New System.Exception(ex.ToString)
End Try
End Sub
I tried casting the object to
Dim qus = CType(ViewState("questions"), IQueryable(Of PM_SelectRandomQuestionFMResult))
but then I get this error
System.Linq.Enumerable+WhereSelectEnumerableIterator`2
Please HELP or if there is any other method to do it, if my method of doing online test is wrong.
Regards
IMO, you're over-engineering this. Why screw around trying to hold the data in memory? Why not write each question to a div, and then hide all of the question divs except for the "current question".
Much easier to implement and you're not hitting the server with several AJAX calls, This also make saving state (previously answered questions, etc) much, much easier.
Have you tried just using Session to maintain state? Is there a requirement that prohibits you from doing this?
Dim qus = CType(Me.Session("questions"), IQueryable(Of PM_SelectRandomQuestionFMResult))

Resources