I am trying to use one of the best example for checking the username availability from the below site
http://www.highoncoding.com/Articles/439_Performing_Instant_UserName_Availability_Check_Using_JQuery_Ajax_API.aspx
And It's just verifying with some pre-initiated names but I wan't to try with my database can anyone suggest me how to proceed further.
Here is the code:
<script language="javascript" type="text/javascript">
var userName = '';
$(document).ready(function()
{
$("#txtUserName").blur(function()
{
userName = $(this).val();
if(userName.length <= 6)
{
$("#display").text("username must be atleast 7 characters");
$("#display").css("background-color","red");
}
else
{
$.ajax(
{
type:"POST",
url:"AjaxService.asmx/CheckUserNameAvailability",
data:"{\"userName\":\"" + userName + "\"}",
dataType:"json",
contentType:"application/json",
success: function(response)
{
if(response.d == true)
{
$("#display").text("username is available");
$("#display").css("background-color","lightgreen");
}
else
{
$("#display").text("username is already taken");
$("#display").css("background-color","red");
}
}
});
}
});
});
</script>
This AjaxService.asmx:
Imports System.Collections
Imports System.ComponentModel
Imports System.Data
Imports System.Linq
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Xml.Linq
Imports System.Collections.Generic
Namespace JQueryUserNameAvailability
<WebService([Namespace] := "http://tempuri.org/")> _
<WebServiceBinding(ConformsTo := WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
<System.Web.Script.Services.ScriptService> _
Public Class AjaxService
Inherits System.Web.Services.WebService
<WebMethod> _
Public Function CheckUserNameAvailability(userName As String) As Boolean
Dim userNames As List(Of [String]) = New List(Of String)() From { _
"azamsharp", _
"johndoe", _
"marykate", _
"alexlowe", _
"scottgu" _
}
Dim user = (From u In userNames Where u.ToLower().Equals(userName.ToLower())u).SingleOrDefault(Of [String])()
Return If([String].IsNullOrEmpty(user), True, False)
End Function
End Class
End Namespace
Modified code:
Public Function CheckUserNameAvailability(ByVal userName As String) As Boolean
Dim strSql As String = String.Format("SELECT COUNT(UserNameCol) FROM Registration WHERE UserNameCol = '{0}'", userName)
Dim strConnection As String = "Data Source=.\sqlexpress;Initial Catalog=Users;Integrated Security=True"
Dim sqlConn As New SqlConnection(strConnection)
Dim sqlDataAdap As New SqlDataAdapter(strSql, sqlConn)
Dim dt As New DataTable()
sqlDataAdap.Fill(dt)
If Convert.ToInt32(dt.Rows(0)(0)) > 0 Then
Return False
End If
Return True
End Function
Modify your CheckUserNameAvailability function to get data from the table where you have saved all the username. An example:
Public Function CheckUserNameAvailability(userName As String) As Boolean
Dim strSql as String = String.Format("SELECT COUNT(userNameCol) FROM users WHERE userNameCol = '{0}'", userName)
Dim sqlConn as new SqlConnection(SQL Connection String)
Dim sqlDataAdap as new SqlDataAdapter(strSql, sqlConn)
Dim dt as new DataTable()
sqlDataAdap.Fill(dt)
If Convert.ToInt32(dt.Rows(0)(0)) > 0 Then
Return false
End If
Return true
End Function
Related
Good morning, I need to encrypt my querystring and i found an interesting method in this link and I convert it in vb.net:
Imports System
Imports System.IO
Imports System.Web
Imports System.Text
Imports System.Security.Cryptography
Public Class QueryStringModule
Implements IHttpModule
Public Sub Dispose() Implements IHttpModule.Dispose
End Sub
Public Sub Init(ByVal context As HttpApplication) Implements IHttpModule.Init
AddHandler context.BeginRequest, New EventHandler(AddressOf context_BeginRequest)
End Sub
Private Const PARAMETER_NAME As String = "enc="
Private Const ENCRYPTION_KEY As String = "key"
Private Sub context_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
Dim context As HttpContext = HttpContext.Current
If context.Request.Url.OriginalString.Contains("aspx") AndAlso context.Request.RawUrl.Contains("?") Then
Dim query As String = ExtractQuery(context.Request.RawUrl)
Dim path As String = GetVirtualPath()
If query.StartsWith(PARAMETER_NAME, StringComparison.OrdinalIgnoreCase) Then
Dim rawQuery As String = query.Replace(PARAMETER_NAME, String.Empty)
Dim decryptedQuery As String = Decrypt(rawQuery)
context.RewritePath(path, String.Empty, decryptedQuery)
ElseIf context.Request.HttpMethod = "GET" Then
Dim encryptedQuery As String = Encrypt(query)
context.Response.Redirect(path & encryptedQuery)
End If
End If
End Sub
Private Shared Function GetVirtualPath() As String
Dim path As String = HttpContext.Current.Request.RawUrl
path = path.Substring(0, path.IndexOf("?"))
path = path.Substring(path.LastIndexOf("/") + 1)
Return path
End Function
Private Shared Function ExtractQuery(ByVal url As String) As String
Dim index As Integer = url.IndexOf("?") + 1
Return url.Substring(index)
End Function
Private ReadOnly Shared SALT As Byte() = Encoding.ASCII.GetBytes(ENCRYPTION_KEY.Length.ToString())
Public Shared Function Encrypt(ByVal inputText As String) As String
Dim rijndaelCipher As RijndaelManaged = New RijndaelManaged()
Dim plainText As Byte() = Encoding.Unicode.GetBytes(inputText)
Dim SecretKey As PasswordDeriveBytes = New PasswordDeriveBytes(ENCRYPTION_KEY, SALT)
Using encryptor As ICryptoTransform = rijndaelCipher.CreateEncryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16))
Using memoryStream As MemoryStream = New MemoryStream()
Using cryptoStream As CryptoStream = New CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)
cryptoStream.Write(plainText, 0, plainText.Length)
cryptoStream.FlushFinalBlock()
Return "?" & PARAMETER_NAME & Convert.ToBase64String(memoryStream.ToArray())
End Using
End Using
End Using
End Function
Public Shared Function Decrypt(ByVal inputText As String) As String
Dim rijndaelCipher As RijndaelManaged = New RijndaelManaged()
Dim encryptedData As Byte() = Convert.FromBase64String(inputText)
Dim secretKey As PasswordDeriveBytes = New PasswordDeriveBytes(ENCRYPTION_KEY, SALT)
Using decryptor As ICryptoTransform = rijndaelCipher.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16))
Using memoryStream As MemoryStream = New MemoryStream(encryptedData)
Using cryptoStream As CryptoStream = New CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)
Dim plainText As Byte() = New Byte(encryptedData.Length - 1) {}
Dim decryptedCount As Integer = cryptoStream.Read(plainText, 0, plainText.Length)
Return Encoding.Unicode.GetString(plainText, 0, decryptedCount)
End Using
End Using
End Using
End Function
End Class
but also my project use FriendlyUrls and I figured out that with FriendlyUrls the things does not working and always return the url without the extension ".aspx" but with the querystring not encrypted
Imports System.Web.Routing
Imports Microsoft.AspNet.FriendlyUrls
Public Module RouteConfig
Sub RegisterRoutes(ByVal routes As RouteCollection)
Dim settings As FriendlyUrlSettings = New FriendlyUrlSettings() With {
.AutoRedirectMode = RedirectMode.Permanent
}
routes.EnableFriendlyUrls(settings)
End Sub
End Module
of course if I set .AutoRedirectMode to Off it works but without friendlyurls.
Am I doing something wrong?
EDIT 09/10/2019:
We figured out that remove the test of OriginalString.Contains("aspx") in the context_BeginRequest the encryption works, now the code is like:
Private Sub context_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
Dim context As HttpContext = HttpContext.Current
If context.Request.RawUrl.Contains("?") Then
Dim query As String = ExtractQuery(context.Request.RawUrl)
Dim path As String = GetVirtualPath()
If query.StartsWith(PARAMETER_NAME, StringComparison.OrdinalIgnoreCase) Then
Dim rawQuery As String = query.Replace(PARAMETER_NAME, String.Empty)
Dim decryptedQuery As String = Decrypt(rawQuery)
context.RewritePath(path, String.Empty, decryptedQuery)
ElseIf context.Request.HttpMethod = "GET" Then
Dim encryptedQuery As String = Encrypt(query)
context.Response.Redirect(path & encryptedQuery)
End If
End If
End Sub
But now the question is: there is other method to target an aspx page without test the extension? I think there is a risk that targeting things that not should target like "ashx" or cache-busting code that use querystring.
Before inserting the record to the table,the system will check first if the first name and last name of the person is already exists. If the person is existing, a message box will appear with yes or no button asking if the user want to continue inserting the record.I have tried the following code:
Imports ChurchMIS.Data
Imports System
Imports System.Collections.Generic
Imports System.Data
Imports System.Linq
Imports System.Text.RegularExpressions
Imports System.Web
Imports System.Web.Security
Imports System.Data.SqlClient
Namespace ChurchMIS.Rules
Partial Public Class IndividualBusinessRules
Inherits ChurchMIS.Data.BusinessRules
''' <summary>
''' This method will execute in any view for an action
''' with a command name that matches "SQL".
''' </summary>
<Rule("r107")> _
Public Sub r107Implementation( _
ByVal individualId As Nullable(Of Integer), _
ByVal firstName As String, _
ByVal lastName As String, _
ByVal dateOfBirth As Nullable(Of DateTime), _
ByVal addressTypeId As Nullable(Of Integer), _
ByVal suburb As String, _
ByVal streetAddress As String, _
ByVal postCode As Nullable(Of Integer), _
ByVal contactInfoTypeId As Nullable(Of Integer), _
ByVal contactNo As String, _
ByVal fullName As String, _
ByVal individualTypeId As Nullable(Of Integer), _
ByVal state As String, _
ByVal dateOfBaptism As Nullable(Of DateTime), _
ByVal dateOfTransfer As Nullable(Of DateTime), _
ByVal email As String, _
ByVal faithStatus As Nullable(Of Integer), _
ByVal noOfVisits As Nullable(Of Integer), _
ByVal name As String, _
ByVal name_1 As String, _
ByVal name_2 As String)
'This is the placeholder for method implementation.
Dim con As SqlConnection = New SqlConnection("Data Source=CNEPHILS;Initial Catalog=ChurchMIS;User ID=sa;Password=Cn$phil$")
Dim theQuery As String = "SELECT * FROM Individual WHERE FirstName=#FirstName AND LastName=#LastName"
Dim cmd1 As SqlCommand = New SqlCommand(theQuery, con)
cmd1.Parameters.AddWithValue("#FirstName", firstName)
cmd1.Parameters.AddWithValue("#LastName", lastName)
Using reader As SqlDataReader = cmd1.ExecuteReader()
If reader.HasRows Then
' person already exists
Dim result As Integer=
Dim result As Integer = MessageBox.Show("message", "caption", MessageBoxButtons.YesNoCancel)
If result = DialogResult.Cancel Then
MessageBox.Show("Cancel pressed")
ElseIf result = DialogResult.No Then
MessageBox.Show("No pressed")
ElseIf result = DialogResult.Yes Then
Dim cmd As SqlCommand = New SqlCommand("exec spInsertIndividual #FirstName,#LastName,#DateOfBirth,#Suburb,#StreetAddress,#PostCode,#State,#AddressTypeId,#ContactInfoTypeId,#ContactNo,#IndividualTypeId,#Email,#FaithStatus,#DateOfBaptism,#DateOfTransfer", con)
cmd.ExecuteNonQuery()
MsgBox("Records Successfully Added!", MsgBoxStyle.Information)
End If
Else
' person does not exist, add them
Dim cmd As SqlCommand = New SqlCommand("exec spInsertIndividual #FirstName,#LastName,#DateOfBirth,#Suburb,#StreetAddress,#PostCode,#State,#AddressTypeId,#ContactInfoTypeId,#ContactNo,#IndividualTypeId,#Email,#FaithStatus,#DateOfBaptism,#DateOfTransfer", con)
cmd.ExecuteNonQuery()
MsgBox("Records Successfully Added!", MsgBoxStyle.Information)
End If
End Using
con.Close()
End Sub
End Class
End Namespace
However,i raised an error "MessageBox is not declared.....protection level."
Hope someone could help. Thanks!
#roger. I think your are working in web application. try this, add this script in your .aspx page inside the head tag.
<script type="text/javascript">
function SomeMethod() {
try {
var result = true;
var obj = {};
obj.Firstname = $('#<%=txtfirstname.ClientID %>').val();
obj.Lastname = $('#<%=txtlastname.ClientID %>').val();
$.ajax({
type: "POST",
data: JSON.stringify(obj),
url: "yourformname.aspx/yourmethodname",
contentType: "application/json; charset=utf-8",
dataType: "json",
async:false,
success: function (response) {
if (response.d.toString() == "true") {
if (confirm("first name and last name of the person is already exists?")) {
result = true;
// insert the user name
}
else {
result = false;
}
}
else {
}
},
failure: function (response) {
alert(response.d);
}
});
}
catch (e) {
alert(e);
}
return result;
}
</script>
call the javascript function in your button click event. if your are using RequiredFieldValidator for validation use the Page_ClientValidate() other wise remove that Page_ClientValidate() function in the button onclick event.
<asp:Button ID="btnbutton" CssClass="Designclass" OnClientClick="if(Page_ClientValidate()) return SomeMethod();"
runat="server" Text="Generate" />
create the following web method in your .aspx.vb page
<System.Web.Services.WebMethod()>
Public Shared Function Checkuserexists(ByVal Firstname As String, ByVal Lastname As String) As String
'write your code for checking firstname and last name
If exists > 0 Then
Return true
Else
Return False
End If
End Function
By using Checkuserexists method check the firstname and last name is exists in the database. if the first name and last name exists its returns true and ask for conform message. if you click yes its insert the value into the database.
I have searched for days, but I can't get my answer, so I create this post.
I developed a web app, so the user can create event in their Google Calendar. It is working. But, I can't figure, why this app only asks the user credential once.
For example:
User John access the .aspx page then he redirected to Google Authorized page because it's the first time John access the page.
After Authorized, John can create an event in his Google Calendar.
It works until this step. The problem occurred when John logout from his google account.
If Dave accesses this page from another computer, he's not redirected to Google Authorized page and suddenly directly creates an event in
JOHN's Calendar.
Can someone help me, why this problem occurred?
this is my code:
Protected Sub new_authentication()
Dim datafolder As String = Server.MapPath("App_Data/CalendarService.api.auth.store")
Dim scopes As IList(Of String) = New List(Of String)()
Dim UserId As String = "GoogleID_co"
scopes.Add(CalendarService.Scope.Calendar)
Dim myclientsecret As New ClientSecrets() With { _
.ClientId = myClientID, _
.ClientSecret = ClientSecret _
}
Dim flow As GoogleAuthorizationCodeFlow
flow = New GoogleAuthorizationCodeFlow(New GoogleAuthorizationCodeFlow.Initializer() With { _
.DataStore = New FileDataStore(datafolder), _
.ClientSecrets = myclientsecret, _
.Scopes = scopes _
})
Dim uri As String = Request.Url.ToString()
Dim code = Request("code")
If code IsNot Nothing Then
Dim token = flow.ExchangeCodeForTokenAsync(UserId, code, uri.Substring(0, uri.IndexOf("?")), CancellationToken.None).Result
' Extract the right state.
Dim oauthState = AuthWebUtility.ExtracRedirectFromState(flow.DataStore, UserId, Request("state")).Result
Response.Redirect(oauthState)
Else
Dim result = New AuthorizationCodeWebApp(flow, uri, uri).AuthorizeAsync(UserId, CancellationToken.None).Result
If result.RedirectUri IsNot Nothing Then
' Redirect the user to the authorization server.
Response.Redirect(result.RedirectUri)
Else
' The data store contains the user credential, so the user has been already authenticated.
myCalendarservice = New CalendarService(New BaseClientService.Initializer() With { _
.ApplicationName = "My Calendar", _
.HttpClientInitializer = result.Credential _
})
createcalendar()
End If
End If
End Sub
This is my createcalendar sub
Protected Sub createcalendar()
Dim newEvent As New [Event]() With { _
.Summary = "Google I/O 2015", _
.Location = "800 Howard St., San Francisco, CA 94103", _
.Description = "A chance to hear more about Google's developer products.", _
.Start = New EventDateTime() With { _
.DateTime = DateTime.Parse("2015-07-13T09:00:00-07:00"), _
.TimeZone = "America/Los_Angeles" _
}, _
.[End] = New EventDateTime() With { _
.DateTime = DateTime.Parse("2015-07-14T17:00:00-07:00"), _
.TimeZone = "America/Los_Angeles" _
}, _
.Recurrence = New [String]() {"RRULE:FREQ=DAILY;COUNT=2"}, _
.Attendees = New EventAttendee() {New EventAttendee() With { _
.Email = "lpage#example.com" _
}, New EventAttendee() With { _
.Email = "sbrin#example.com" _
}}, _
.Reminders = New [Event].RemindersData() With { _
.UseDefault = False, _
.[Overrides] = New EventReminder() {New EventReminder() With { _
.Method = "email", _
.Minutes = 24 * 60 _
}, New EventReminder() With { _
.Method = "sms", _
.Minutes = 10 _
}} _
} _
}
Dim calendarId As [String] = "primary"
Dim request As EventsResource.InsertRequest = myCalendarservice.Events.Insert(newEvent, calendarId)
Dim createdEvent As [Event] = request.Execute()
End Sub
I resolved my problem. I found that the name of token always same that's why this problem occurred. So, just replace this code:
Dim datafolder As String = Server.MapPath("App_Data/CalendarService.api.auth.store")
Dim scopes As IList(Of String) = New List(Of String)()
Dim UserId As String = "GoogleID_co"
into
Dim datafolder As String = Server.MapPath("App_Data/CalendarService.api.auth.store")
Dim scopes As IList(Of String) = New List(Of String)()
Dim UserId As String = "GoogleID_co" & {unique Identifier such as userid,username,etc}
In my asp.net web service, I have an object class which get data from database, but I counter the following problem when some data is null in database:
(1) If I don't handle the NULL value in database and use the code as below:
<WebMethod> _
Public Function GetCustomerDetail(ByVal sqlQuery As String) As List(Of customerInfo)
Dim detaillist = New List(Of customerInfo)()
Dim detail As customerInfo
Dim da = New SqlDataAdapter(sqlQuery, conn)
Dim dt = New DataTable()
da.Fill(dt)
For Each dr As DataRow In dt.Rows
detail = New customerInfo() With { _
.CustomerID = dr("CUSTOMER_ID"), _
.CustomerName = dr("CUSTOMER_NAME"), _
.RegisterDate = dr("REGISTER_DATE"), _
.Address = dr("ADDRESS") _
}
detaillist.Add(detail)
Next
Return detaillist
End Function
Public Class customerInfo
Public CustomerID As String = String.Empty
Public CustomerName As String = String.Empty
Public RegisterDate As String = Date.Now.ToString("dd/MM/yyyy")
Public Address As String = String.Empty
End Class
I got the error:
System.InvalidCastException: Conversion from type 'DBNull' to type 'String' is not valid.
(2) if I handle the NULL in database as below:
<WebMethod> _
Public Function GetCustomerDetail(ByVal sqlQuery As String) As List(Of customerInfo)
Dim detaillist = New List(Of customerInfo)()
Dim detail As customerInfo
Dim da = New SqlDataAdapter(sqlQuery, conn)
Dim dt = New DataTable()
da.Fill(dt)
For Each dr As DataRow In dt.Rows
detail = New customerInfo() With { _
.CustomerID = dr("CUSTOMER_ID"), _
.CustomerName = dr("CUSTOMER_NAME"), _
.RegisterDate = dr("REGISTER_DATE"), _
If dr("ADDRESS") = System.DBNull.Value Then
.Address = ""
Else
.Address = dr("ADDRESS") _
End if
}
detaillist.Add(detail)
Next
Return detaillist
End Function
Public Class customerInfo
Public CustomerID As String = String.Empty
Public CustomerName As String = String.Empty
Public RegisterDate As String = Date.Now.ToString("dd/MM/yyyy")
Public Address As String = String.Empty
End Class
I got the error:
Compiler Error Message: BC30985: Name of field or property being initialized in an object initializer must start with '.'.
I want to know how to handle the DBNull value for string and date in an object initializer.
You can use Convert.ToString
<WebMethod> _
Public Function GetCustomerDetail(ByVal sqlQuery As String) As List(Of customerInfo)
Dim detaillist = New List(Of customerInfo)()
Dim detail As customerInfo
Dim da = New SqlDataAdapter(sqlQuery, conn)
Dim dt = New DataTable()
da.Fill(dt)
For Each dr As DataRow In dt.Rows
Dim registerDate As Date
If Date.TryParse(Convert.ToString(dr("REGISTER_DATE")), registerDate ) = False Then
'Do what you need to do if the cell is not a valid date time value
End If
detail = New customerInfo() With { _
.CustomerID = Convert.ToString(dr("CUSTOMER_ID")), _
.CustomerName = Convert.ToString(dr("CUSTOMER_NAME")), _
.RegisterDate = registerDate.ToString("dd/MM/yyyy"), _
.Address = Convert.ToString(dr("ADDRESS"))
}
detaillist.Add(detail)
Next
Return detaillist
End Function
Edited based on OP's comment below.
While the other methods would work, I think a re-usable extension method with generics support would be ideal.
You can pass the work off to the extension method and check if the value is equal to the value of DBNull.Value
Public Module DataRowExtensions
<System.Runtime.CompilerServices.Extension>
Public Function GetValueOrDefault(Of TExpectedType)(dr As DataRow, propertyName As String) As TExpectedType
If DBNull.Value.Equals(dr(propertyName)) Then
Return Nothing
End If
Return DirectCast(dr(propertyName), TExpectedType)
End Function
End Module
You can see this DotNetFiddle to see it in action with various data types.
Do make note that the extension method Field<T> does exist and is similar, but it doesn't handle DBNull values.
You can't use an if statement inside an object initializer like that.
You have to instantiate the object, then set the properties in separate lines.
detail = New customerInfo()
'Then in separate lines, populate the properties individually
If dr("ADDRESS") = System.DBNull.Value Then
detail.Address = ""
Else
detail.Address = dr("ADDRESS")
guys. I'm developing a website with ASP and VB.NET 4. I'm also using the FullCalendar jQuery plugin, but I have a trouble: catching a parameter from querystring to the webmethod in the .asmx. I've tried to refer the querystring property with the Request.QueryString() and it doesn't work.
Here's the webmethod:
<%# WebService Language="VB" Class="wbsCalendario" %>
Imports System.Web
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Web.Script.Services
Imports System.Collections.Generic
Imports System.Configuration.ConfigurationManager
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)>
<ScriptService> _
Public Class wbsCalendario
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function ListarEventos(ByVal starte As String, ByVal ende As String, ByVal v As String) As List(Of CalendarioEvento)
Dim conexaoSql As New SqlConnection(ConnectionStrings("praeConnectionString").ConnectionString)
Dim comandoSql As SqlCommand = New SqlCommand("spListarEventosCalendario", conexaoSql)
comandoSql.CommandType = CommandType.StoredProcedure
comandoSql.Parameters.AddWithValue("#bitPendentes", 0)
comandoSql.Parameters.AddWithValue("#agendamentos", "188,135")
comandoSql.Parameters.AddWithValue("#start", FromUnixTimespan(starte))
comandoSql.Parameters.AddWithValue("#end", FromUnixTimespan(ende))
comandoSql.Parameters.AddWithValue("#veiculo", v)
Dim eventos As List(Of CalendarioEvento) = New List(Of CalendarioEvento)
Try
conexaoSql.Open()
Dim sdrEventos As SqlDataReader = comandoSql.ExecuteReader
While sdrEventos.Read
Dim evento As New CalendarioEvento
evento.title = StrConv(sdrEventos("vchNome").ToString, VbStrConv.ProperCase)
evento.start = ToUnixTimespan(Convert.ToDateTime(sdrEventos("vchData") + " " + sdrEventos("vchHora")))
eventos.Add(evento)
End While
Catch ex As Exception
Finally
conexaoSql.Close()
End Try
comandoSql.Parameters("#bitPendentes").Value = 1
Try
conexaoSql.Open()
Dim sdrEventos As SqlDataReader = comandoSql.ExecuteReader
While sdrEventos.Read
Dim evento As New CalendarioEvento
evento.title = StrConv(sdrEventos("vchNome").ToString, VbStrConv.ProperCase)
evento.start = ToUnixTimespan(Convert.ToDateTime(sdrEventos("vchData") + " " + sdrEventos("vchHora")))
evento.color = "#6AB0D8"
eventos.Add(evento)
End While
Catch ex As Exception
Finally
conexaoSql.Close()
End Try
Return eventos
End Function
Private Shared Function ToUnixTimespan(ByVal d As DateTime) As Long
Dim time As New TimeSpan()
time = d.ToUniversalTime().Subtract(New DateTime(1970, 1, 1, 0, 0, 0))
Return CType(Math.Truncate(time.TotalSeconds), Int64)
End Function
Private Shared Function FromUnixTimespan(ByVal s As String) As DateTime
Dim time As DateTime = New DateTime(1970, 1, 1, 0, 0, 0)
Return time.AddSeconds(s)
End Function
End Class
Can someone help me?
Thanks.
The values in the query string are automatically translated into arguments defined on the webmethod.
If you had this Webmethod:
<WebMethod()> Public Sub DoWork(arg1 As Integer, arg2 As String)
And called it by a url of:
http://domain/webservice.asmx/DoWork?arg=2&arg2=hello
Those two querystring parameters would be translated into the two arguments arg1 and arg2, which could be referenced as normal within the DoWork() method.