Trying to get a querystring variable with an ashx - asp.net

I have been trying to sort this out all day with lots of Googling but with little effect so thanks in advance if you read and are able to help.
I have a simple page which allows a user to select files and upload to an Amazon bucket, the first page looks like this:
var checkError = false;
$(window).load(
function () {
$("#<%=FileImages.ClientID %>").fileUpload({
'fileSizeLimit': '100MB',
'uploader': 'scripts/uploader.swf',
'cancelImg': 'images/cancel.png',
'buttonText': 'Upload Files',
'script': 'UploadVB.ashx?gid=56',
'folder': 'uploads',
'multi': true,
'auto': true,
'onAllComplete': function (uploads) {
if (!checkError) {
location.href = "finished";
}
},
'onComplete': function (event, ID, fileObj, response, data) {
if (200 != parseInt(response)) {
checkError = true;
$('#FileImages' + ID).addClass('uploadifyError');
$('#FileImages' + ID + ' .percentage').text(' - ' + response);
return false;
}
}
});
}
);
Note the gid=56. It then sends the files over to UploadVB.ashx and this looks like this:
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim awsRegion As Amazon.RegionEndpoint = Amazon.RegionEndpoint.EUWest1
Dim client As New AmazonS3Client(System.Configuration.ConfigurationManager.AppSettings("AWSAccessKey").ToString(), System.Configuration.ConfigurationManager.AppSettings("AWSSecretKey").ToString(), awsRegion)
Dim fileID As String = Guid.NewGuid().ToString("N")
Dim postedFile As HttpPostedFile = context.Request.Files("Filedata")
Dim galleryid = context.Request.QueryString("gid")
Try
Dim filename As String = Path.GetFileName(postedFile.FileName)
'### I WANT TO SUBMIT THE FILENAME AND ID INTO A TABLE HERE ######
AddPortfolioPhoto(filename, Convert.ToInt16(galleryid))
'#################################################################
Dim S3_KEY As [String] = filename.Replace(" ", "")
Dim request As New PutObjectRequest()
With request
.BucketName = System.Configuration.ConfigurationManager.AppSettings("AWSBucketName").ToString()
.Key = S3_KEY
.InputStream = postedFile.InputStream
End With
client.PutObject(request)
context.Response.Write("200")
context.Response.StatusCode = 200
Catch ex As Exception
context.Response.Write("AWS ERROR :: " + ex.Message)
End Try
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
Every time I run this above it just doesn't do anything, If I remove this line:
AddPortfolioPhoto(filename, Convert.ToInt16(galleryid))
it works great but it is crucial I get this inserted into the database someway and I just can't seem to be able to grab the gid value.
Any help is greatly appreciated.
Public Shared Sub AddPortfolioPhoto(ByVal fn As String, gid As Integer)
Dim Writer As New Data.SqlClient.SqlCommand
Writer.CommandType = Data.CommandType.StoredProcedure
Writer.CommandText = "BCMS_AddGalleryPhoto"
Writer.Connection = New Data.SqlClient.SqlConnection(System.Configuration.ConfigurationManager.AppSettings("sqlstr"))
Writer.Parameters.AddWithValue("#imgstr", Data.SqlTypes.SqlString.Null).Value = fn
Writer.Parameters.AddWithValue("#galleryid", Data.SqlTypes.SqlInt32.Null).Value = gid
Writer.Parameters.AddWithValue("#so", Data.SqlTypes.SqlInt32.Null).Value = 0
Writer.Parameters.AddWithValue("#featured", Data.SqlTypes.SqlInt32.Null).Value = 0
Writer.Prepare()
Writer.Connection.Open()
Writer.ExecuteNonQuery()
Writer.Connection.Close()
End Sub

Looks like with your help I may have gotten to the bottom of this, the value I was expecting (56) wasn't what I was actually getting, I was actually getting "uploads" in the same variable so sending a string down to this method was never going to work, thanks #matt-dot-net for suggesting and thanks Andrew Morton for the tip on dispose, I will use that rather than close.

Related

Consuming Webservice - Sending Signature- Error X509Certificate2 type was not expected

I'm consume an external webservice for sending data, using a web application in asp.net and Visual Studio 2010. The
sending of data must be digitally signed using a digital signature. The webservice contains the Signature class, where I
can fill all required values ​​(SignedInfo, SignatureValue, KeyInfo).
I'm trying to fill the KeyInfo structure with the certificate like this:
Dim Sig As New RSP.SignatureType
(...)
Sig.SignedInfo = Sig_info
(...)
Sig.SignatureValue = Sig_value
Dim rspKey_info As New RSP.KeyInfoType()
Dim rspX509 As New RSP.X509DataType()
Dim arrCertificate As X509Certificate2()
arrCertificate = myF.ReturnCertificateCC()
rspKey_info.ItemsElementName = New RSP.ItemsChoiceType2(0) {}
rspKey_info.ItemsElementName(0) = RSP.ItemsChoiceType2.X509Data
rspKey_info.Items = New Object(0) {}
rspX509.ItemsElementName = New RSP.ItemsChoiceType2(0) {}
rspX509.ItemsElementName(0) = RSP.ItemsChoiceType2.X509Data
rspX509.Items = New Object(0) {}
rspX509.Items(0) = arrCertificate (0)
Sig.KeyInfo = rspKey_info
xmlString = myF.SerializeAnObject(Sig)
When I try to serialize the Signature Object, an error occur:
"Error generating the XML document."
InnerException:
"{ " The System.Security.Cryptography.X509Certificates.X509Certificate2 type was not expected . Use XmlInclude or
SoapInclude attribute to specify types that are not known statically. "}"
Public Function SerializeAnObject(ByVal obj As Object) As String
Dim doc As System.Xml.XmlDocument = New XmlDocument()
Dim serializer As System.Xml.Serialization.XmlSerializer = New System.Xml.Serialization.XmlSerializer(obj.GetType())
Dim stream As System.IO.MemoryStream = New System.IO.MemoryStream()
Try
serializer.Serialize(stream, obj)
stream.Position = 0
doc.Load(stream)
Return doc.InnerXml
Catch ex As Exception
Return ""
Finally
stream.Close()
stream.Dispose()
End Try
'#utilização
'dim xmlObject As string = SerializeAnObject(myClass)
End Function
Please help me...
I'm at several days trying to solve this...
Thanks in advance!
Regards!
rspX509.ItemsElementName = New RSP.ItemsChoiceType(0) {}
rspX509.ItemsElementName(0) = RSP.ItemsChoiceType.X509Certificate
rspX509.Items = New Object(0) {}
rspX509.Items(0) = arrCertificate (0)
rspKey_info.Items(0) = rspX509

ASP IF Logic not fully functioning

I have a login form that checks for roles and when the credentials are met, the user is directed to a specific page. My issue is that when the username or password is incorrect, my logic fails to prompt the user via a label that I have in the design. I even tried implementing it via a Try/Catch and still the same result.
The Design:
<div><asp:Label ID="lblinfo" runat="server" Width="374px" CssClass="blktext"></asp:Label></div>
The code in behind the (button event-handler):
Try
Dim con As New SqlConnection(GetConnectionString())
con.Open()
Dim cmd As New SqlCommand("Check_Users", con)
cmd.CommandType = CommandType.StoredProcedure
Dim p1 As New SqlParameter("Login_name", username.Text)
Dim p2 As New SqlParameter("Login_Pwd", password.Text)
cmd.Parameters.Add(p1)
cmd.Parameters.Add(p2)
Dim rd As SqlDataReader = cmd.ExecuteReader()
'check the Role of the user logging in'
While (rd.Read())
Session("numrecord") = rd.GetValue(0).ToString()
rd.GetValue(11).ToString()
If rd.HasRows Then
If rd.GetValue(11).ToString() = 1 Then
rd.Read()
lblinfo.Text = "You are Authorized."
FormsAuthentication.RedirectFromLoginPage(username.Text, True)
Response.Redirect("securepages/SecurePage.aspx")
Else
lblprompt.Text = "Invalid username or password."
End If
If rd.GetValue(11).ToString() = 2 Then
rd.Read()
FormsAuthentication.RedirectFromLoginPage(username.Text, True)
Response.Redirect("securepages/newShipment.aspx")
Else
lblprompt.Text = "Invalid username or password."
End If
End If
End While
Catch ex As Exception
lblprompt.Text = "Invalid username or password."
End Try
Could I get some help as to what am failing to do here?
At the very least, please write a basic POCO object to encapsulate the values from the data layer.
Use your datareader to POPULATE the Poco object, and insert some basic logic on the Poco object.
Use the datareader quickly, then get rid of it.
Then you could actually reuse the object and your logic.
Something like this.
Then (in the presentation layer) ~respond to the values in the Poco with the redirects and such.
public enum RedirectTypeEnum
{
Unknown = 0,
SecurePage = 1,
NewShipment = 2,
}
public class LoginAttemptResult
{
public LoginAttemptResult()
{
this.NumRecord = 0;
this.ResultNumberAkaColumn11 = 0;
}
public int NumRecord { get; set; }
public int ResultNumberAkaColumn11 { get; set; }
public RedirectTypeEnum RedirectType
{
get
{
RedirectTypeEnum returnValue = RedirectTypeEnum.Unknown;
if (this.ResultNumberAkaColumn11 == 1)
{
returnValue = RedirectTypeEnum.SecurePage;
}
if (this.ResultNumberAkaColumn11 == 2)
{
returnValue = RedirectTypeEnum.NewShipment;
}
return returnValue;
}
}
public bool IsAuthorized
{
get
{
if (this.ResultNumberAkaColumn11 == 1)
{
return true;
}
if (this.ResultNumberAkaColumn11 == 2)
{
return false; /* ?? */
}
return false;
}
}
}
Then you'll have one place where you populate this object, and someone can see clearly what the biz logic is by looking at the POCO object.
One issue that I see is that you are response.redirect'ing in a Try...Catch block. Unless you put , False (which allows the code to finish executing instead of aborting) after the URL, you will throw a Thread is aborting error every time it attempts to redirect.
As for the message not showing, you show how lblinfo is created, but what about lblprompt? Perhaps you have its visible property set to false? If this is the case, make sure to change it to true in the code. Also, make sure you are not clearing its value on events such as page_load.
I have also cleaned up the code a little bit and implemented a datatable object instead of the reader:
Try
Dim cmd As New SqlCommand("Check_Users", New SqlConnection(GetConnectionString()))
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add(New SqlParameter("Login_name", username.Text))
cmd.Parameters.Add(New SqlParameter("Login_Pwd", password.Text))
Dim sqlDataAdapter As New SqlClient.SqlDataAdapter(cmd)
Dim dtResults As New DataTable
sqlDataAdapter.Fill(dtResults)
lblprompt.Text = "Invalid username or password."
'check the Role of the user logging in'
If dtResults.Rows.Count > 0 Then
With dtResults.Rows(0)
Session("numrecord") = .Item(0).ToString()
If .Item(11).ToString() = 1 Then
lblprompt.Text = ""
FormsAuthentication.RedirectFromLoginPage(username.Text, True)
Response.Redirect("securepages/SecurePage.aspx", False)
ElseIf .Item(11).ToString() = 2 Then
lblprompt.Text = ""
FormsAuthentication.RedirectFromLoginPage(username.Text, True)
Response.Redirect("securepages/newShipment.aspx", False)
End If
End With
End If
Catch ex As Exception
lblprompt.Text = "An error has occurred." & ex.Message
End Try

hexadecimal value 0x1F, is an invalid character

I am getting the following error:
' ', hexadecimal value 0x1F, is an invalid character
Here is my function. I get this error when it hits "reader.MoveToContent()" for the first time. Can anyone point me in the right direction?
Public Function GetSyndicationFeedData(ByVal urlFeedLocation As String) As SyndicationFeed
Dim settings As New XmlReaderSettings() With { _
.IgnoreWhitespace = True, _
.CheckCharacters = True, _
.CloseInput = True, _
.IgnoreComments = True, _
.IgnoreProcessingInstructions = True _
}
If [String].IsNullOrEmpty(urlFeedLocation) Then
Return Nothing
End If
Using reader As XmlReader = XmlReader.Create(urlFeedLocation, settings)
If reader.ReadState = ReadState.Initial Then
reader.MoveToContent()
End If
' Now try reading...
Dim atom As New Atom10FeedFormatter()
Dim rss20 As New Rss20FeedFormatter()
' Atom
If atom.CanRead(reader) Then
atom.ReadFrom(reader)
Return atom.Feed
'Rss 2.0
ElseIf rss20.CanRead(reader) Then
rss20.ReadFrom(reader)
Return rss20.Feed
Else
Return Nothing
End If
End Using
End Function
You can use the following code (sorry but it is in c#) to download the feed and replace the offending character.
var client = new WebClient();
var feedAsString = client.DownloadString(urlFeedLocation).Replace((char)(0x1F), Convert.ToChar(""));
using (XmlReader reader = XmlReader.Create(new MemoryStream(Encoding.Default.GetBytes(feedAsString)), settings))
{
// remainder of your code here
}

How to Store Data in Client Side Database in JSON Web Services

I have a Client side page and i have fields like empname,address,sex etc., if we click on Create button the Employee data should store in Database..For that purpose i write a class "EmployeeModel" and taken fields written properties and in client side i added service reference and in that .aspx.cs i writeen something like this:
EmployeeModel emp = new EmployeeModel();
emp.FirstName = txtFirstName.Text;
emp.LastName = txtLastName.Text;
emp.Address = txtAddress.Text;
emp.DateOfBirth1 = txtDOB.Text;
emp.Sex = rdbtnGender.SelectedItem.ToString();
After that what steps i have to write to store Employee data in DATABASE.
First you need to make call from client side to server using below javascript code
$.ajax({
type: "get",
url: "?ajax_mode=SaveMyData,
dataType: "json",
async: false,
data: { headerData: JSON.stringify(emp) },
cache: false,
success: function(data, textStatus) {
if (data.status == "success") {
}
else {
}
}
});
Now handle savemydata function to save info of employee
Public Sub SaveMyData()
Dim objHeaderPostData As Dictionary(Of String, Object)
Dim strParams As String = Request("headerData")
Dim objOutput As New Ajax.BasicAjaxObjectOuput
Dim jsS As New JavaScriptSerializer : objHeaderPostData = CType(jsS.DeserializeObject(strParams), Dictionary(Of String, Object))
Dim strFirstName as string = CStr(objHeaderPostData.Item("FirstName"))
'' get same way other infor from object objHeaderPostData
Dim objOutput As New BasicOuputObject
Dim objCommand As New SqlCommand
Dim lstMyData As New List(Of MyData)
Dim objMyData As MyData
Dim objConn As New SqlConnection("Pass Connection String")
objCommand.CommandText = '' write insert or update command as per requirement
objCommand.Connection = objConn
objConn.Open()
objCommand.ExecuteScalar()
objOutput.errorMessage = ""
objOutput.obj = "Successfylly save record."
objOutput.strMessage = "success"
Dim objSerialiser As New System.Web.Script.Serialization.JavaScriptSerializer
HttpContext.Current.Response.Write(objSerialiser.Serialize(objOutput))
HttpContext.Current.Response.End()
End Sub
Hope this will help you.
more info about json you can visit my blog here

Google calendar in vb.net

I am trying to convert the calendar code of C#.NET provided on google site to VB.NET and facing some conversion issues. Please help me.
Code in C#.net:
static void RetrieveAcls(CalendarService service)
{
FeedQuery query = new FeedQuery();
query.Uri = new Uri("http://www.google.com/calendar/feeds/testingforfinals#gmail.com");
AtomFeed calFeed = service.Query(query);
Console.WriteLine();
Console.WriteLine("Sharing permissions for your calendars:");
// Retrieve the meta-feed of all calendars.
foreach (AtomEntry calendarEntry in calFeed.Entries)
{
Console.WriteLine("Calendar: {0}", calendarEntry.Title.Text);
AtomLink link = calendarEntry.Links.FindService(
AclNameTable.LINK_REL_ACCESS_CONTROL_LIST, null);
// For each calendar, retrieve its ACL feed.
if (link != null)
{
AclFeed feed = service.Query(new AclQuery(link.HRef.ToString()));
foreach (AclEntry aclEntry in feed.Entries)
{
Console.WriteLine("\tScope: Type={0} ({1})", aclEntry.Scope.Type,
aclEntry.Scope.Value);
Console.WriteLine("\tRole: {0}", aclEntry.Role.Value);
}
}
}
}
My code in VB.NET:
Public Sub RetrieveAcls(ByVal service As CalendarService)
Dim query As New FeedQuery
query.Uri = New Uri("http://www.google.com/calendar/feeds/testingforfinals#gmail.com")
Dim calFeed As New AtomFeed(service.Query(query))
Console.WriteLine()
Console.WriteLine("Sharing permissions for your calendars:")
Dim calendarEntry As New AtomEntry
Dim link As New AtomLink
Dim aclEntry As New AclEntry
For Each calendarEntry In calFeed.Entries
Console.WriteLine("Calendar: {0}", calendarEntry.Title.Text)
link = calendarEntry.Links.FindService(AclNameTable.LINK_REL_ACCESS_CONTROL_LIST, "")
If (link Is Nothing) Then
Dim feed As AclFeed()
feed = New AclFeed(query, service)
feed = service.Query(New AclQuery(link.HRef.ToString()))
For Each aclEntry In feed.Entries
Console.WriteLine("\tScope: Type={0} ({1})", aclEntry.Scope.Type, aclEntry.Scope.Value)
Console.WriteLine("\tRole: {0}", aclEntry.Role.Value)
Next
End If
Next
End Sub
Am facing error at "query" in "feed = New AclFeed(query, service)" which says Value of type Google.GData.Client.FeedQuery cannot be converted to 'System.Uri'... This issue is resolved... One more last issue is as per below...
Dim myQuery As New EventQuery(feedURI)
Dim myResultsFeed As New EventFeed(service.Query(myQuery))
I am getting error on "myResultsFeed" as "Argument not specified for parameter 'iService' of 'Public Sub New(uriBase As System.Uri, iService As Google.GData.Client.IService)'." and another error on "service.Query(myQuery)) as "Value of type 'Google.GData.Calendar.EventFeed' cannot be converted to 'System.Uri'."
static void DateRangeQuery(CalendarService service, DateTime startTime, DateTime endTime)
{
EventQuery myQuery = new EventQuery(feedUri);
myQuery.StartTime = startTime;
myQuery.EndTime = endTime;
EventFeed myResultsFeed = service.Query(myQuery) as EventFeed;
Console.WriteLine("Matching events from {0} to {1}:",
startTime.ToShortDateString(),
endTime.ToShortDateString());
Console.WriteLine();
for (int i = 0; i < myResultsFeed.Entries.Count; i++)
{
Console.WriteLine(myResultsFeed.Entries[i].Title.Text);
}
Console.WriteLine();
}
Well you've converted this:
AclFeed feed = service.Query(new AclQuery(link.HRef.ToString()));
to this:
Dim feed As AclFeed()
feed = New AclFeed(query, service)
feed = service.Query(New AclQuery(link.HRef.ToString()))
They're not the same at all! Your second line is calling a constructor for no obvious reason.
Just this would be fine:
Dim feed As AclFeed = service.Query(New AclQuery(link.HRef.ToString()))
It's also not clear why you've got lines like this:
Dim calendarEntry As New AtomEntry
Why are you calling the parameterless constructor for AtomEntry? Why are you declaring the variable outside the ForEach loop at all? Just use:
For Each calendarEntry As AtomEntry In calFeed.Entries
EDIT: For the other issue, I think you just need:
Dim myEventFeed As CType(service.Query(myQuery), EventFeed)
If you could provide the full method, that would help.
I'm not sure if it works, but this is the direct c#->VB.Net-Translation from developerfusion, the syntax seems to be correct. Only as a hint for your next problems ;)
Shared Sub RetrieveAcls(ByVal service As CalendarService)
Dim query As New FeedQuery()
query.Uri = New Uri("http://www.google.com/calendar/feeds/testingforfinals#gmail.com")
Dim calFeed As AtomFeed = service.Query(query)
Console.WriteLine()
Console.WriteLine("Sharing permissions for your calendars:")
' Retrieve the meta-feed of all calendars.
For Each calendarEntry As AtomEntry In calFeed.Entries
Console.WriteLine("Calendar: {0}", calendarEntry.Title.Text)
Dim link As AtomLink = calendarEntry.Links.FindService(AclNameTable.LINK_REL_ACCESS_CONTROL_LIST, Nothing)
' For each calendar, retrieve its ACL feed.
If Not link Is Nothing Then
Dim feed As AclFeed = service.Query(New AclQuery(link.HRef.ToString()))
For Each aclEntry As AclEntry In feed.Entries
Console.WriteLine(vbTab & "Scope: Type={0} ({1})", aclEntry.Scope.Type, aclEntry.Scope.Value)
Console.WriteLine(vbTab & "Role: {0}", aclEntry.Role.Value)
Next
End If
Next
End Sub

Resources