I am using rails4. I added a carrierwave gem. There is an error using carrierwave. I am uploading file in ticket model.
When I go to new ticket it throws a error-uninitialized constant Ticket::Asset.
tickets controller
class TicketsController < ApplicationController
before_action :require_signin!
before_action :set_project
before_action :set_ticket, only: [:show, :edit, :update, :destroy]
before_action :authorize_create!, only: [:new, :create]
before_action :authorize_update!, only: [:edit, :update]
before_action :authorize_delete!, only: :destroy
def new
#ticket = #project.tickets.build
3.times {#ticket.assets.build}
end
def edit
end
def create
#ticket = #project.tickets.build(ticket_params)
#ticket.user = current_user
if #ticket.save
flash[:notice] = "Ticket has been created."
redirect_to [#project, #ticket]
else
flash[:alert] = "Ticket has not been created."
render "new"
end
end
def update
if #ticket.update(ticket_params)
flash[:notice] = "Ticket has been updated."
redirect_to [#project, #ticket]
else
flash[:alert] = "Ticket has not been updated."
render action: "edit"
end
end
def destroy
#ticket.destroy
flash[:notice] = "Ticket has been deleted."
redirect_to #project
end
private
def ticket_params
params.require(:ticket).permit(:title, :description, assets_attributes:[:asset])
end
def set_project
#project =Project.find(params[:project_id])
end
def set_ticket
#ticket = #project.tickets.find(params[:id])
end
end
class Ticket < ActiveRecord::Base
has_many :assets
belongs_to :project
belongs_to :user
accepts_nested_attributes_for :assets
validates :title, :description, presence: true
end
asset model
class Asset < ActiveRecord::Base
mount_uploader :asset, AssetUploader
belongs_to :ticket
end
routes
Ticketee::Application.routes.draw do
resources :users
resources :projects do
resources :tickets
end
I missed to generate the uploader file. It solved my problem.
Related
Since I'm unable to add a .vb code-behind file to my .aspx page, as delineated here, I'm trying to add the method "inline" like so (the "ConvertSubcategoryIndex" function is the new bit of code):
<%
. . .
If Request.Form.Item("Action") = "Save" Then
. . .
.Parameters.Add("#Subcategory", SqlDbType.NVarChar).Value = ConvertSubcategoryIndex(Category, Subcategory)
. . .
End If 'If Save Action
Function ConvertSubcategoryIndex(_Category As String, _Subcategory As Int32) As String
If _Category = "New"
If _Subcategory = 0
Return "New"
End If
Else If _Subcategory = 1
Return "Assumed"
End If
End If
If _Category = "Existing"
If _Subcategory = 0
Return "Existing"
End If
Else If _Subcategory = 1
Return "Organic"
End If
End If
Return "Unknown"
End Function
%>
That doesn't work, though, and I get this:
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: BC30289: Statement cannot appear within a method body. End of method assumed.
Source Error:
Line 274: End If 'If Save Action
Line 275:
Line 276: Function ConvertSubcategoryIndex(_Category As String, _Subcategory As Int32) As String
Line 277: If _Category = "New"
Line 278: If _Subcategory = 0
Source File: C:\Users\cshannon\Source\Workspaces\CSReports\EnhancedMonthlySalesReporting\customerreportingnet\customerreportingnet\pages\custmaint_entry.aspx Line: 276
NOTE: I get this whether I put the function above or below End If 'If Save Action
UPDATE
Based on somebody's alias (NoAlias), I tried adding a section at the top with the code like so:
. . .
</head>
<%
Function ConvertSubcategoryIndex(_Category As String, _Subcategory As Int32) As String
If _Category = "New"
If _Subcategory = 0
Return "New"
End If
Else If _Subcategory = 1
Return "Assumed"
End If
End If
If _Category = "Existing"
If _Subcategory = 0
Return "Existing"
End If
Else If _Subcategory = 1
Return "Organic"
End If
End If
Return "Unknown"
End Function
%>
<%
Unit = Request.QueryString.Item("Unit")
. . .
...but it made no difference; I still get, "Statement cannot appear within a method body. End of method assumed."
UPDATE 2
Even with the improved code from tgolisch:
Function ConvertSubcategoryIndex(_Category As String, _Subcategory As Int32) As String
If _Category = "New" Then 'really need a "Then" for every "If"
If _Subcategory = 0 Then
Return "New"
'End If 'this End If was killing the next line
ElseIf _Subcategory = 1 Then
Return "Assumed"
End If
End If
If _Category = "Existing" Then
If _Subcategory = 0 Then
Return "Existing"
'End If 'this one was causing problems too
ElseIf _Subcategory = 1 Then 'ElseIf can't have a space between Else If
Return "Organic"
End If
End If
Return "Unknown"
End Function
...I get the same err msg as before:
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: BC30289: Statement cannot appear within a method body. End of method assumed.
Source Error:
Line 63: <%
Line 64: 'End Sub
Line 65: Function ConvertSubcategoryIndex(_Category As String, _Subcategory As Int32) As String
Line 66: If _Category = "New" Then 'really need a "Then" for every "If"
Line 67: If _Subcategory = 0 Then
Source File: C:\Users\cshannon\Source\Workspaces\CSReports\EnhancedMonthlySalesReporting\customerreportingnet\customerreportingnet\pages\custmaint_entry.aspx Line: 65
Weirder yet, Visual Studio finds a problem with the first line of the code, and makes the bizarre suggestion that I prepend an "End Sub" there:
I tried that, just for yuks, but as might be suspected, that raised an err of its own, elsewhere.
UPDATE 3
Based on both answers (tgolisch's fixing the code itself, and Sam Axe's showing how it needs to be added to the mix), it is now working. With those fixes and fixes to my logic, in its working state it is:
<script runat="Server">
Function ConvertSubcategoryIndex(_Category As String, _Subcategory As String) As String
If _Category = "New Business" Then
If _Subcategory = "0" Then
Return "New"
ElseIf _Subcategory = "1" Then
Return "Assumed"
End If
End If
If _Category = "Existing Business" Then
If _Subcategory = "0" Then
Return "Existing"
ElseIf _Subcategory = "1" Then
Return "Organic"
End If
End If
Return "Unknown"
End Function
</script>
I haven't done WebForms in ages... but if memory serves you need to use something like:
<script runat="Server">
Public Function Whatever() As String
Return "something"
End Function
</script>
Your VB.NET syntax had several syntax errors. Try pasting this code for your ConvertSubcategoryIndex() function:
<%
Function ConvertSubcategoryIndex(_Category As String, _Subcategory As Int32) As String
If _Category = "New" Then 'really need a "Then" for every "If"
If _Subcategory = 0 Then
Return "New"
'End If 'this End If was killing the next line
ElseIf _Subcategory = 1 Then
Return "Assumed"
End If
End If
If _Category = "Existing" Then
If _Subcategory = 0 Then
Return "Existing"
'End If 'this one was causing problems too
ElseIf _Subcategory = 1 Then 'ElseIf can't have a space between Else If
Return "Organic"
End If
End If
Return "Unknown"
End Function
%>
You also might need to take a look at the quality of the code at the top of your first example. I can't tell what is happening where you put ....
I have System.Type object (retType). I get this with Reflection from my policy object that I pass in . How can I test to see if its enumerable? Any help would be most appreciated code is below.
Public Shared Function SerializeChanges(p As Model.Policy_2.Policy) As XmlDocument
Dim polProps As PropertyInfo() = p.GetType().GetProperties()
For Each pi As PropertyInfo In polProps
Dim retType As Type = pi.PropertyType
' This line belowthrows an error that IEnumerable is an Interface and cannot be used as an expression
If retType Is IEnumerable Then
'Do Stuff
End If
End Function
The following method is a generic method to check whether a given type inherits or implements another type:
Function InheritsOrImplements(child As Type, parent As Type) As Boolean
If child Is Nothing OrElse parent Is Nothing Then
Return False
End If
parent = resolveGenericTypeDefinition(parent)
If parent.IsAssignableFrom(child) Then
Return True
End If
Dim currentChild = If(child.IsGenericType, child.GetGenericTypeDefinition(), child)
While currentChild <> GetType(Object)
If parent = currentChild OrElse hasAnyInterfaces(parent, currentChild) Then
Return True
End If
currentChild = If(currentChild.BaseType IsNot Nothing AndAlso currentChild.BaseType.IsGenericType, currentChild.BaseType.GetGenericTypeDefinition(), currentChild.BaseType)
If currentChild Is Nothing Then
Return False
End If
End While
Return False
End Function
Function hasAnyInterfaces(parent As Type, child As Type) As Boolean
Return child.GetInterfaces().Any(Function(childInterface)
Dim currentInterface = If(childInterface.IsGenericType, childInterface.GetGenericTypeDefinition(), childInterface)
Return currentInterface = parent
End Function)
End Function
Function resolveGenericTypeDefinition(type As Type) As Type
Dim shouldUseGenericType = Not (type.IsGenericType AndAlso type.GetGenericTypeDefinition() <> type)
If type.IsGenericType AndAlso shouldUseGenericType Then
type = type.GetGenericTypeDefinition()
End If
Return type
End Function
Taken from https://github.com/shaynevanasperen/Quarks/blob/master/Quarks/TypeExtensions/InheritsOrImplements.cs
Usage:
InheritsOrImplements(retType, GetType(IEnumerable))
i want to send email using Persits.MailSender object. i found one solution and i include this code this solution works and Object created:
<%
posted = request.form ("submit")
if posted = "Submit" then
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'' Customize the following 5 lines with your own information. ''
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
vtoaddress = "_____" ' Change this to the email address you will be receiving your notices.
vmailhost = Application("ServerAddress") ' Change this to your actual Domain name.
vfromaddress = "_____" ' Change this to the email address you will use to send and authenticate with.
vfrompwd = "_______________" ' Change this to the above email addresses password.
vsubject = "ASP Contact Form" 'Change this to your own email message subject.
'''''''''''''''''''''''''''''''''''''''''''
'' DO NOT CHANGE ANYTHING PAST THIS LINE ''
'''''''''''''''''''''''''''''''''''''''''''
vfromname = request.form ("TName")
vbody = request.form ("TBody")
vrplyto = request.form ("TEmail")
vmsgbody = vfromname &"<br>"& vrplyto &"<br>"& vbody
Set objEmail = Server.CreateObject("Persits.MailSender")
objEmail.Username = vfromaddress
objEmail.Password = vfrompwd
objEmail.Host = vmailhost
objEmail.From = vfromaddress
objEmail.AddAddress vtoaddress
objEmail.Subject = vsubject
objEmail.Body = vmsgbody
objEmail.IsHTML = True
objEmail.Send
vErr = Err.Description
if vErr <> "" then
response.write vErr & "<br><br>There was an error on this page."
else
response.write "Thank you, your message has been sent."
End If
Set objEmail = Nothing
response.write "Thank you, your message has been sent."
end if
%>
<html><body>
<form name="SendEmail01" method="post">
<table border=0>
<tr>
<td>Name:</td>
<td><input type="text" name="TName" size="30"></td>
</tr>
<tr>
<td>Email:</td>
<td><input type="text" name="TEmail" size="30"></td>
</tr>
<tr>
<td>Body:</td>
<td><textarea rows="4" name="TBody" cols="30"></textarea></td>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit"></td>
</tr>
</form>
</body></html>
after filling all fields and submitting page then error occured like:
Persits.MailSender.4 error '800a0004'
Cannot assign requested address.
/contact_form.asp, line 34
please help me..
I hope so this piece of code will help you
<%
Class HVMailer
Private mMail
Private Sub Class_Initialize()
Set mMail = Server.CreateObject("Persits.MailSender")
mMail.Host = ""
mMail.Username = ""
mMail.Password = ""
mMail.TLS = True
End Sub
Public Property Let FromAddress(sFrom)
mMail.From = trim(sFrom)
End Property
Public Property Let FromName(sFromName)
mMail.FromName = trim(sFromName)
End Property
Public Property Let ReplyTo(sReply)
mMail.AddReplyTo trim(sReply), trim(sReply)
End Property
Public Property Let Subject(sSubject)
mMail.Subject = sSubject
End Property
Public Property Let BodyText(sBodyText)
mMail.Body = sBodyText
End Property
Public Property Let HTML(bHTML)
mMail.isHTML = bHTML
End Property
Public Sub AddRecipient(sAddress, sName)
sAddress = trim(sAddress)
if mMail.ValidateAddress(sAddress)= 0 Then
mMail.AddAddress sAddress, sName
end if
End Sub
Public Sub AddCC(sAddress, sName)
sAddress = trim(sAddress)
if mMail.ValidateAddress(sAddress)= 0 Then
mMail.AddCC sAddress, sName
end if
End Sub
Public Sub AddBCC(sAddress, sName)
sAddress = trim(sAddress)
if mMail.ValidateAddress(sAddress)= 0 Then
mMail.AddBCC sAddress, sName
end if
End Sub
Public Sub AddAttachment(sFile)
mMail.AddAttachment sFile
End Sub
Public function Send()
On Error Resume Next
mReturn = True
mMail.Send
if Err<>0 Then
mReturn = false
end if
Set mMail = Nothing
send = mReturn
End Function
End Class
%>
I am trying to spawn a new thread from an ASP page written in VB.NET, on .NET 3.5.
The page allows a user to upload files and then processes the files into the database.
As the processing can take a while, I want to upload them, spawn the processing onto a new thread, and then when it completes send the user a notification through our database-driven notification module in the system.
I've tried a couple different examples I've found online, but they don't seem to work. There is no error thrown, but it never seems to actually launch the processing code on a new thread either.
Here is my submittal code in the web page:
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
Try
If Not (file1.HasFile Or file2.HasFile Or file3.HasFile Or file4.HasFile Or file5.HasFile) Then
AddErrorMessage("Please specify at least one file.")
Else
Dim l = New List(Of InventoryUploads.File)
If file1.HasFile Then l.Add(New InventoryUploads.File With {.Name = file1.FileName, .Content = file1.FileContent})
If file2.HasFile Then l.Add(New InventoryUploads.File With {.Name = file2.FileName, .Content = file2.FileContent})
If file3.HasFile Then l.Add(New InventoryUploads.File With {.Name = file3.FileName, .Content = file3.FileContent})
If file4.HasFile Then l.Add(New InventoryUploads.File With {.Name = file4.FileName, .Content = file4.FileContent})
If file5.HasFile Then l.Add(New InventoryUploads.File With {.Name = file5.FileName, .Content = file5.FileContent})
InventoryUploads.ProcessFiles(l, Session.UserIdent, chkRcvOverwrite.Checked)
NewRow("Your files have been queued and are being processed. You will be sent a notification when they are completed.")
End If
Catch ex As Exception
LogEx(ex)
NewRow("There was an error queueing your files." & BR & ex.Message)
End Try
End Sub
From a UI point of view, this all works, the page posts the files, and it shows the user the message about "your files have been queued".
The call to InventoryUploads.ProcessFiles is an encapsulation function in front of the threading code, which is all contained in the InventoryUploads module (following):
Imports System.Threading
Imports System.Threading.Tasks
Public Module InventoryUploads
Public Structure File
Private pName As String
Private pContent As IO.Stream
Private pProcessed As Boolean
Public Property Name As String
Get
Return pName
End Get
Set(value As String)
pName = value
End Set
End Property
Public Property Content As IO.Stream
Get
Return pContent
End Get
Set(value As IO.Stream)
pContent = value
End Set
End Property
Public Property Processed As Boolean
Get
Return pProcessed
End Get
Set(value As Boolean)
pProcessed = value
End Set
End Property
End Structure
Public Sub ProcessFiles(files As List(Of File), userident As String, receivingsOverwrite As Boolean)
Try
Dim params = Array.CreateInstance(GetType(Object), 3)
params(0) = files
params(1) = userident
params(2) = receivingsOverwrite
'// Threading Method 1
Dim pts = New ParameterizedThreadStart(AddressOf ThreadedProcessFiles)
Dim thd = New Thread(pts)
thd.IsBackground = True
thd.Start(params)
'// Threading Method 2
'ThreadPool.QueueUserWorkItem(AddressOf ThreadedProcessFiles, params)
'// Threading Method 3
Dim f As Func(Of Integer) = Function() ThreadedProcessFiles(params)
Task.Factory.StartNew(f)
Catch ex As Exception
IO.File.WriteAllText("C:\idwherenet.log", ex.Message)
Throw
End Try
End Sub
''' <summary>
'''
''' </summary>
''' <param name="params">exepcts params to contain 3 objects,
''' 1) type List(Of File),
''' 2) string userident to notify on finish
''' 3) boolean whether receivings should overwrite</param>
''' <remarks></remarks>
Private Function ThreadedProcessFiles(params() As Object) As Boolean
IO.File.WriteAllText("C:\mylog.log", "hello ThreadedProcessFiles?")
'Log("threadedprocessfiles: got here")
Dim files As List(Of File), uident As String = "", rcvovr As Boolean
Try
files = params(0)
uident = CStr(params(1))
rcvovr = CBool(params(2))
If files.Count = 0 Then
SendNotification(NotificationTypes.SYS, uident, "No files provided for inventory upload; nothing processed.")
Exit Sub
End If
For Each f In files
f.Processed = False
If f.Content.Length = 0 Then Continue For
'// process the file here....
f.Processed = True
Next
SendNotification(NotificationTypes.SYS, uident, "Inventory upload processing completed.")
Return True
Catch ex As Exception
'LogEx(ex)
'Log(ex.Message, ex.ToString)
If Not uident.IsEmpty Then SendNotification(NotificationTypes.SYS, uident, "Inventory upload processing encountered an error. " & ex.Message, ex.ToString)
Return False
End Try
End Sub
End Module
In the ProcessFiles sub, you can see the three different methods I have tried to spawn the thread, including a NuGet backport of the Task Parallel Library... neither works. I have confirmed that is is making it into the ProcessFiles sub, and the code to spawn the thread is not throwing any errors... it just never actually calls the ThreadedProcessFiles function.
Any ideas?
UPDATE: Oh, actually, the NuGet package DOES seem to be working, FINALLY! It just doesn't write out to the file (context/security/impersonation permissions I guess). Now I can finally move on!
If you're using .NET 4 or 4.5, the Task Parallel Library makes this sort of thing super easy:
Task.Factory.StartNew(Function() ThreadedProcessFiles(params));
(I think that's the right syntax for VB)
If you go this route, I would change the params to just send the three parameters separately.
In .Net you can use reflection to get access to an enumeration of all properties of a class. Can this be done too with a VB6 class module?
Found it!
You need to set a reference to the TypeLib library (tlbinf32.dll) and then you can use code like (this is class module):
EDIT: Unfortunately, while the code below works as expected when run in debug mode inside the VB6 IDE, it fails when compiled. After compiling any attempt to read the .Members propery causes an 'Object doesn't support this action' error (445). I have given up on it, unless someone can make the code below work both in and outside of the IDE.
Option Explicit
Private TLI As TLIApplication
Private m_clsInterface As InterfaceInfo
Private m_clsClassUnderInvestigation As Object
Private Sub Class_Terminate()
Set m_clsClassUnderInvestigation = Nothing
Set m_clsInterface = Nothing
Set TLI = Nothing
End Sub
Public Sub FillListBoxWithMembers(pList As ListBox, Optional pObject As Object)
Dim lMember As MemberInfo
If pObject = Empty Then
Set pObject = ClassUnderInvestigation
End If
Set m_clsInterface = TLI.InterfaceInfoFromObject(pObject)
For Each lMember In m_clsInterface.Members
pList.AddItem lMember.Name & " - " & WhatIsIt(lMember)
Next
Set pObject = Nothing
End Sub
Public Function GetPropertyLetNames() As Collection
Dim filters(1 To 1) As InvokeKinds
filters(1) = INVOKE_PROPERTYPUT
Set GetPropertyLetNames = Filter(filters)
End Function
Public Function GetPropertySetNames() As Collection
Dim filters(1 To 1) As InvokeKinds
filters(1) = INVOKE_PROPERTYPUTREF
Set GetPropertySetNames = Filter(filters)
End Function
Public Function GetPropertyLetAndSetNames() As Collection
Dim filters(1 To 2) As InvokeKinds
filters(1) = INVOKE_PROPERTYPUT
filters(2) = INVOKE_PROPERTYPUTREF
Set GetPropertyLetAndSetNames = Filter(filters)
End Function
Public Function GetPropertyGetNames() As Collection
Dim filters(1 To 1) As InvokeKinds
filters(1) = INVOKE_PROPERTYGET
Set GetPropertyGetNames = Filter(filters)
End Function
Private Function Filter(filters() As InvokeKinds) As Collection
Dim Result As New Collection
Dim clsMember As MemberInfo
Dim i As Integer
For Each clsMember In m_clsInterface.Members
For i = LBound(filters) To UBound(filters)
If clsMember.InvokeKind = filters(i) Then
Result.Add clsMember.Name
End If
Next i
Next
Set Filter = Result
End Function
Private Function WhatIsIt(lMember As Object) As String
Select Case lMember.InvokeKind
Case INVOKE_FUNC
If lMember.ReturnType.VarType <> VT_VOID Then
WhatIsIt = "Function"
Else
WhatIsIt = "Method"
End If
Case INVOKE_PROPERTYGET
WhatIsIt = "Property Get"
Case INVOKE_PROPERTYPUT
WhatIsIt = "Property Let"
Case INVOKE_PROPERTYPUTREF
WhatIsIt = "Property Set"
Case INVOKE_CONST
WhatIsIt = "Const"
Case INVOKE_EVENTFUNC
WhatIsIt = "Event"
Case Else
WhatIsIt = lMember.InvokeKind & " (Unknown)"
End Select
End Function
Private Sub Class_Initialize()
Set TLI = New TLIApplication
End Sub
Public Property Get ClassUnderInvestigation() As Object
Set ClassUnderInvestigation = m_clsClassUnderInvestigation
End Property
Public Property Set ClassUnderInvestigation(clsClassUnderInvestigation As Object)
Set m_clsClassUnderInvestigation = clsClassUnderInvestigation
Set m_clsInterface = TLI.InterfaceInfoFromObject(m_clsClassUnderInvestigation)
End Property
I am heavily endebted to this post.