undefined method `original_filename' for Upload - ruby-on-rails-3

Can't seem to identify why I would be getting a undefined method original_filename, trying to do a file upload that checks the file extensions. Any ideas where im going wrong here
class SpreadsheetTagService
include Roo
def initialize(uploaded_file)
open_spreadsheet(File.new(uploaded_file.tempfile.path))
read_file(open_spreadsheet)
end
private
def read_file(file)
#spreadsheet = open_spreadsheet(file)
#spreadsheet.each_with_pagename do |name,sheet|
Rails.logger.debug( sheet )
end
end
def open_spreadsheet(file)
case File.extname(file.path)
when ".csv" then Csv.new(file.path, nil, :ignore)
when ".xls" then Excel.new(file.path, nil, :ignore)
when ".xlsx" then Excelx.new(file.path, nil, :ignore)
else raise "Unknown file type: #{file.original_filename}"
end
end
end
Controller
class SpreadsheetServiceController < ApplicationController
def new
end
def create
parser = SpreadsheetTagService.new(params[:spreadsheet][:file])
respond_to do |format|
format.all {render :json => 'Done'}
end
end
end

This one worked for me, removed the #{file.original_filename} from raise exception, modified the code so the file extension is saved properly:
class SpreadsheetTagService
include Roo
def initialize(uploaded_file)
ext = File.extname(uploaded_file.original_filename)
#tmp_destination = "#{Rails.root}/tmp/tag-import#{ext}"
#file_path = save_file_to_tmp(uploaded_file)
#file = File.new(#file_path)
read_file(#file)
end
private
def save_file_to_tmp(uploaded_file)
FileUtils.mv(uploaded_file.tempfile, #tmp_destination )
#tmp_destination
end
def read_file(file)
#spreadsheet = open_spreadsheet(file)
#spreadsheet.each_with_pagename do |name,sheet|
Rails.logger.debug( sheet )
end
end
def open_spreadsheet(file)
case File.extname(file.path)
when ".csv" then Csv.new(file.path, nil, :ignore)
when ".xls" then Excel.new(file.path, nil, :ignore)
when ".xlsx" then Excelx.new(file.path, nil, :ignore)
else raise "Unknown file type"
end
end
end

Related

VSTO MailItem.Save error “The operation cannot be performed because the message has been changed”

I am trying to change categories color of a current selected mail in outlook 2013 using the explorer object to get the current selected item. Everything seems to be well except when I save it gives the error mentioned above. I have been looking for solutions and no luck any ideas? Thanks. here is my code in VB
Private Sub exp_SelectionChange() Handles exp.SelectionChange ' errrrorr
Try
waitapprovemail = Application.Session.GetItemFromID(exp.Selection.Item(1).EntryID)
if (CheckForRedCategory(waitapprovemail)) Then
If (CheckToReleaseMail(waitapprovemail)) Then
waitapprovemail.Categories = "Green Category"
waitapprovemail.Save() ''' this gives the error
End If
End If
Catch Exc As System.Runtime.InteropServices.COMException
MsgBox(Exc.Message & " " & Exc.Source)
Catch exc As System.InvalidCastException
MsgBox("Casting problem")
End Try
End Sub
Private Function CheckToReleaseMail(mail As MailItem) As Boolean ' errrrrr
' check the id with the ids in the locked mail, if found id then check the other flag if it is false or true, if found true then set the category of that waitemail to empty "" else keep it
Dim r As Boolean = True
Dim sarray As String()
' ofile2 = fso2.OpenTextFile("C:\Users\" & userName & "\Documents\Outlook Files\LockedMail.txt", 8, True) '8 for appending in arg2 0 for tristatefalse optional opens as ascii
Try
Using sr As New StreamReader("C:\Users\" & userName & "\Documents\Outlook Files\LockedMail.txt")
Dim line As String
Do
line = sr.ReadLine()
If (line.Equals("") Or line Is Nothing) Then
r = True
Continue Do
Else
sarray = line.Split(",")
If (sarray.Count > 0) Then
If (sarray(0).Equals(mail.EntryID, StringComparison.InvariantCultureIgnoreCase)) Then
r = False
sr.Close()
mail.Close(OlInspectorClose.olDiscard)
Return r
End If
End If
End If
Loop Until line Is Nothing
sr.Close()
End Using
Catch exc As System.Exception
End Try
mail.Close(OlInspectorClose.olDiscard)
Return r
End Function
Private Function CheckForRedCategory(mail As MailItem) As Boolean ' errrrrr
Dim b As Boolean = False
Try
If (mail.Categories.Equals("Red Category")) Then
b = True
mail.Close(OlInspectorClose.olDiscard)
Return b
Else
b = False
End If
Catch exc As System.NullReferenceException
b = False
mail.Close(OlInspectorClose.olDiscard)
End Try
mail.Close(OlInspectorClose.olDiscard)
Return b
End Function

Error: Unable to read beyond the end of the stream

I have this VB code which is giving the above error in the code below
Try
'Job Ticket Section
StatusText = "Reading Job Ticket Data."
FileName = System.IO.Path.Combine(SoftSavePath, "cfgjt.sys")
If Not System.IO.File.Exists(FileName) Then
CopyDefaultSoftJobTicketItems(FileName, ErrorFlag)
End If
filenumber = FreeFile()
FileOpen(filenumber, FileName, OpenMode.Binary)
.ConvexJobTicketItems = GetConfigConvexJobTicketItems(filenumber)
.ConcaveJobTicketItems = GetConfigConcaveJobTicketItems(filenumber)
FileClose(filenumber)
Catch ex As Exception
ErrorFlag.NumErrors = ErrorFlag.NumErrors + 1
ReDim Preserve ErrorFlag.ErrorDef(ErrorFlag.NumErrors - 1)
With ErrorFlag.ErrorDef(ErrorFlag.NumErrors - 1)
.Number = ErrorFlag.NumErrors - 1
.Description = "Open Config job ticket File Error: " & StatusText + ex.Message
End With
FileClose(filenumber)
End Try
On debugging , I found out that when the cursor hits this statement .ConcaveJobTicketItems , it jumps to the catch block .
The function GetConfigConcaveJobTicketItems(filenumber) where I stepped into has other function calls inside it .
Public Function GetConfigConcaveJobTicketItems(ByRef InFileNumber As Short) As JobTicketConcaveDesignItemsType
With GetConfigConcaveJobTicketItems
.ComfortConic = GetConfigConcaveSphereToricJobTicket(InFileNumber, "ConfortConic")
.Multicurve = GetConfigConcaveSphereToricJobTicket(InFileNumber, "Multicurve")
End With
End Function
When the debug cursor Hits the statement .ComfortConic = GetConfigConcaveSphereToricJobTicket(InFileNumber, "ConfortConic"), I step into the function and see that everything is fine and the cursor moves to the next line.
.Multicurve = GetConfigConcaveSphereToricJobTicket(InFileNumber, "Multicurve")
The GetConfigConcaveSphereToricJobTicket() is defined as
Public Function GetConfigConcaveSphereToricJobTicket(ByRef InFileNumber As Short, ByRef InString As String) As JobTicketSphereToricConcaveItemsType
With GetConfigConcaveSphereToricJobTicket
.Sphere = GetConfigConcaveDesignJobTicket(InFileNumber, InString & "Sphere")
.Toric = GetConfigConcaveDesignJobTicket(InFileNumber, InString & "Toric")
End With
End Function

UserPrincipal.Save() - vshost32.exe has stopped working - Corrupt heap

I'm writing some software to import a CSV file into Active Directory (to create user accounts). At some point I know it was working perfectly importing multiple accounts. I'm not sure what I've changed as it's been a while since I last worked on it. But it now imports 2 accounts successfully and then crashes on the line below during the third loop iteration (however the third account is still created):
newUser.Save()
When it crashes I get the error "vshost32.exe has stopped working". I then enabled native code debugging and now get this error: "0xC0000374: A heap has been corrupted" and InvalidCastException (see immediate window at end of post for full error). For testing I've been deleting and recreating the same accounts. If I don't delete the first three accounts, the principal exists exception is handled and then the program crashes on the 4th iteration, and then the 5th and so on. But it never crashes on the first two. (The data I'm importing is identical except for numbers - E.g. sAMAccountNames: Test1, Test2, Test3 etc)
My Code
Private Sub bwImport_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles bwImport.DoWork
Dim _worker As BackgroundWorker = CType(sender, BackgroundWorker)
Dim beginImport As New StartImport(AddressOf progressForm.StartImport)
Me.Invoke(beginImport, New Object() {dtUsers.Rows.Count})
Dim log As New UpdateLog(AddressOf progressForm.UpdateLog)
'### TO DO: Check that all mandatory columns/attributes are in the DataTable
'### TO DO: Check for duplicate sAMAccountNames, userPrincipalNames and Cononical Names
#If Not Debug Then
Try
#End If
Dim rowNum As Integer = 0 'Keep track of how many accounts have been created
For Each row As DataRow In dtUsers.Rows
Dim newUser As UserPrincipalEx = New UserPrincipalEx(adCtx)
newUser.SamAccountName = row("sAMAccountName")
newUser.SetPassword(row("Password"))
'General Tab (of Template Exporter)
If row.Table.Columns.Contains("initials") Then
newUser.Initials = row("initials")
End If
If row.Table.Columns.Contains("givenName") Then
newUser.GivenName = row("givenName")
End If
If row.Table.Columns.Contains("sn") Then
newUser.Surname = row("sn")
End If
If row.Table.Columns.Contains("displayName") Then
newUser.DisplayName = row("displayName")
End If
If row.Table.Columns.Contains("description") Then
newUser.Description = row("description")
End If
If row.Table.Columns.Contains("physicalDeliveryOfficeName") Then
newUser.Office = row("physicalDeliveryOfficeName")
End If
If row.Table.Columns.Contains("telephoneNumber") Then
newUser.TelephoneNumber = row("telephoneNumber")
End If
If row.Table.Columns.Contains("wWWHomePage") Then
newUser.WebPage = row("wWWHomePage")
End If
'Address Tab (of Template Exporter)
If row.Table.Columns.Contains("streetAddress") Then
newUser.Street = row("streetAddress")
End If
If row.Table.Columns.Contains("postOfficeBox") Then
newUser.POBox = row("postOfficeBox")
End If
If row.Table.Columns.Contains("l") Then 'City
newUser.City = row("l")
End If
If row.Table.Columns.Contains("st") Then 'State/Province
newUser.State = row("st")
End If
If row.Table.Columns.Contains("postalCode") Then
newUser.PostCode = row("postalCode")
End If
'### TO DO: Add country fields
'Account Tab (of Template Exporter)
If row.Table.Columns.Contains("userPrincipalName") Then
newUser.UserPrincipalName = row("userPrincipalName")
End If
If row.Table.Columns.Contains("ResetPassword") Then
If row("ResetPassword").ToString.ToLower = "yes" Then
newUser.ExpirePasswordNow() 'Force the user to change their password at next logon
End If
End If
If row.Table.Columns.Contains("PreventPasswordChange") Then
If row("PreventPasswordChange").ToString.ToLower = "yes" Then
newUser.UserCannotChangePassword = True
End If
End If
If row.Table.Columns.Contains("PasswordNeverExpires") Then
If row("PasswordNeverExpires").ToString.ToLower = "yes" Then
newUser.PasswordNeverExpires = True
End If
End If
If row.Table.Columns.Contains("AccountDisabled") Then
If row("AccountDisabled").ToString.ToLower = "yes" Then
newUser.Enabled = False
Else
newUser.Enabled = True
End If
Else 'Enable the account by default if not specified
newUser.Enabled = True
End If
If row.Table.Columns.Contains("accountExpires") Then
Dim expireyDate As Date
Date.TryParse(row("accountExpires"), expireyDate) 'Try to convert the data from row("accountExpires") into a date
newUser.AccountExpirationDate = expireyDate
End If
'Profile Tab (of Template Exporter)
If row.Table.Columns.Contains("profilePath") Then
newUser.ProfilePath = row("profilePath")
End If
If row.Table.Columns.Contains("scriptPath") Then
newUser.ScriptPath = row("scriptPath")
End If
If row.Table.Columns.Contains("homeDrive") Then
newUser.HomeDrive = row("homeDrive")
End If
If row.Table.Columns.Contains("homeDirectory") Then
newUser.HomeDirectory = row("homeDirectory")
End If
'Telephones Tab (of Template Exporter)
If row.Table.Columns.Contains("homePhone") Then
newUser.HomePhone = row("homePhone")
End If
If row.Table.Columns.Contains("pager") Then
newUser.Pager = row("pager")
End If
If row.Table.Columns.Contains("mobile") Then
newUser.Mobile = row("mobile")
End If
If row.Table.Columns.Contains("facsimileTelephoneNumber") Then
newUser.Fax = row("facsimileTelephoneNumber")
End If
If row.Table.Columns.Contains("ipPhone") Then
newUser.IPPhone = row("ipPhone")
End If
'Organization Tab
If row.Table.Columns.Contains("title") Then
newUser.Title = row("title")
End If
If row.Table.Columns.Contains("department") Then
newUser.Department = row("department")
End If
If row.Table.Columns.Contains("company") Then
newUser.Company = row("company")
End If
rowNum += 1
_worker.ReportProgress(rowNum) 'Update progress dialog
Try
newUser.Save() 'Save the user to Active Directory
Me.Invoke(log, New Object() {"Successfully created " + row("sAMAccountName") + " (" + row("displayName") + ")", frmProgress.LogType.Success})
Catch ex As PrincipalExistsException
Me.Invoke(log, New Object() {"Error creating " + row("sAMAccountName") + " (" + row("displayName") + "). " + ex.Message, frmProgress.LogType.Failure})
Continue For
End Try
'Member Of Tab
If row.Table.Columns.Contains("MemberOf") Then
Dim groups() As String = row("MemberOf").ToString.Split(";")
'Add the user to any specified groups
Dim groupPrincipal As GroupPrincipal
Try 'Try adding group(s)
For Each group As String In groups
groupPrincipal = groupPrincipal.FindByIdentity(adCtx, group) 'Search for the group name, sid, sAMAccountName or display name
If groupPrincipal IsNot Nothing Then
groupPrincipal.Members.Add(newUser) 'Add the user to the group
groupPrincipal.Save()
Else
Me.Invoke(log, New Object() {"Unable to add " + row("sAMAccountName") + " to group: " + group + ". Group not found.", frmProgress.LogType.Failure})
End If
Next
Catch ex As PrincipalExistsException
'### TO DO: Try to get group name in exception
Me.Invoke(log, New Object() {"Error adding " + row("sAMAccountName") + " (" + row("displayName") + ") to " + "group(s). " + ex.Message, frmProgress.LogType.Failure})
End Try
End If
newUser.Dispose() 'Dispose of the newUser object
Next
#If Not Debug Then
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
End Try
#End If
End Sub
Immediate Window (When Native Debugging is enabled)
Critical error detected c0000374
First-chance exception at 0x76fbf996 in AD User Importer.exe: 0xC0000374: A heap has been corrupted.
A first chance exception of type 'System.InvalidCastException' occured in System.DirectoryServices.AccountManagement.dll
I think your issue lies in this block:
Try
newUser.Save() 'Save the user to Active Directory
Me.Invoke(log, New Object() {"Successfully created " + row("sAMAccountName") + " (" + row("displayName") + ")", frmProgress.LogType.Success})
Catch ex As PrincipalExistsException
Me.Invoke(log, New Object() {"Error creating " + row("sAMAccountName") + " (" + row("displayName") + "). " + ex.Message, frmProgress.LogType.Failure})
Continue For
End Try
This code handles exceptions but does not dispose newUser before continuing with the next loop iteration.
I recently began to receive similar heap exceptions and after a close examination I realized that I was not disposing my UserPrincipal object. Once I correctly disposed of the object the issue seems to have stopped.
You should wrap your newUser object in a Using block:
For Each row As DataRow In dtUsers.Rows
Using newUser As UserPrincipalEx = New UserPrincipalEx(adCtx)
newUser.SamAccountName = row("sAMAccountName")
newUser.SetPassword(row("Password"))
' ... the remainder of the code
' ... now wrapped in a Using block
End Using
Next
The newUser object will be automatically disposed no matter how the Using block is exited. Because the Using block disposes for you, you can remove the explicit call to newUser.Dispose().
If the Using block is not available in your version of VB.Net then you should wrap the loop in a Try...Finally block and explicitly dispose the newUser in the Finally block.

How to solve codes after for loop that do not execute in vb.net?

I have this code under my form_load
checkUser = False
MsgBox("test start")
result = Newtonsoft.Json.JsonConvert.DeserializeObject(Of ArrayList)(getJSon("https://dtitdtr.herokuapp.com/employees"))
MsgBox("test after result before for-each")
For Each value As Object In result
token = JObject.Parse(value.ToString())
id = token.SelectToken("id")
fname = token.SelectToken("fname")
mname = token.SelectToken("mname")
lname = token.SelectToken("lname")
contact = token.SelectToken("contactno")
add = token.SelectToken("address")
user = token.SelectToken("username")
pass = token.SeelectToken("password")
If user.ToString().ToUpper().Equals(GetUName()) Then
checkUser = True
Exit For
Else
checkUser = False
End If
Next value
MsgBox("test after next value")
reader.Close()
response.Close()
and when I run the program, the first two(2) message boxes displayed and the last one, which is after the Next Value, won't display.
I don't quite get what's going on; since yerterday, when I run it, it went just fine and right now after adding codes for update info, which does not suppose to affect the form_load, the codes right after for loop won't execute. What is the problem with this?
I got something here that says "an exception is being thrown" but I don't even have a Try Catch in my code.
Hope that your code throws some Exception inside the For, so i suggest you to include Try.. Catch get the exception details. that helps you to detect the problem.
Try
For Each value As Object In result
token = JObject.Parse(value.ToString())
id = token.SelectToken("id")
fname = token.SelectToken("fname")
mname = token.SelectToken("mname")
lname = token.SelectToken("lname")
contact = token.SelectToken("contactno")
add = token.SelectToken("address")
user = token.SelectToken("username")
pass = token.SeelectToken("password")
If user.ToString().ToUpper().Equals(GetUName()) Then
checkUser = True
Exit For
Else
checkUser = False
End If
Next value
MsgBox("test after next value")
reader.Close()
response.Close()
Catch ex As Exception
MsgBox("Exception :" & ex.ToString)
End Try

An Issue in MATLAB with OOP when sending a cell to the method

I am doing a simple test with OOP (Object Oriented Programming) in MATLAB. I made a simple class including a constructor. Additionally, I made three sections regarding properties: three regular properties; one constant; and three dependent properties. I included a couple of get/set methods for regular properties, one output method, and one protected / Static method that is used by the Constructor: 'getPropertyValue(propertyName, inputCell).
The Static method causes a problem. I am sending two parameters: 'propertyName' of string type, and 'inputCell' of cell type. The last argument is supposed to send all input parameters copied from varargin defined in the Constructor.
When I try to use the class and make its instance in the Command Line,
a = FigureObjects('promien',10)
I get this error:
Undefined function 'getPropertyValue' for input arguments of type 'cell'.
Error in FigureObjects (line 26)
[temp,status,msgStatus] = getPropertyValue('podstawa',inputCell);
I though I could send anything to any function such as string, cell, matrix etc. Is there any way to send a cell to this function and read its content?
Thanks
PS. This is my code:
classdef FigureObjects
%FIGUREOBJECTS Summary of this class goes here
% Detailed explanation goes here
properties
podstawa
wysokosc
promien
end
properties (Constant = true, Hidden = true)
liczbaPi = 3.14
end
properties (Dependent = true)
obwodKola
obwodProstokata
obwodKwadratu
end
methods
% Constructor
function obj = FigureObjects(varargin)
inputCell = varargin;
if nargin > 0
[temp,status,msgStatus] = getPropertyValue('podstawa',inputCell);
if status
obj.podstawa = temp;
else
error(msgStatus);
end
[temp,status,msgStatus] = getPropertyValue('wysokosc',inputCell);
if status
obj.wysokosc = temp;
else
error(msgStatus);
end
[temp,status,msgStatus] = getPropertyValue('promien',inputCell);
if status
obj.promien = temp;
else
error(msgStatus);
end
end
end
% get functions
function obwodKola = get.obwodKola(obj)
if ~isempty(obj.promien)
obwodKola = 2*FigureObjects.liczbaPi*obj.promien;
else
error('''promien'' is not defined.');
end
end
function obwodProstokata = get.obwodProstokata(obj)
if (~isempty(obj.podstawa) && ~isempty(obj.wysokosc))
obwodProstokata = 2*(obj.podstawa*obj + obj.wysokosc);
else
error('Either ''podstawa'' or/and ''wysokosc'' are not defined.');
end
end
function obwodKwadratu = get.obwodKwadratu(obj)
if ~isempty(obj.podstawa)
obwodKwadratu = 4*obj.podstawa;
else
error('''podstawa'' is not defined.');
end
end
function promien = get.promien(obj)
promien = obj.promien;
end
function podstawa = get.podstawa(obj)
podstawa = obj.podstawa;
end
function wysokosc = get.wysokosc(obj)
wysokosc = obj.wysokosc;
end
% set functions
function obj = set.promien(obj,promien)
if isnumeric(promien)
obj.promien = promien;
else
error('''promien'' must be numeric.');
end
end
function obj = set.podstawa(obj,podstawa)
if isnumeric(promien)
obj.podstawa = podstawa;
else
error('''podstawa'' must be numeric.');
end
end
function obj = set.wysokosc(obj,wysokosc)
if isnumeric(wysokosc)
obj.wysokosc = wysokosc;
else
error('''wysokosc'' must be numeric.');
end
end
% output functions
function output = obwod(theFigureObj, rodzajFigury)
if strcmpi(rodzajFigury,'kolo')
output = theFigureObj.obwodKola;
elseif strcmpi(rodzajFigury,'prostokat')
output = theFigureObj.obwodProstokata;
elseif strcmpi(rodzajFigury,'kwadrat')
output = theFigureObj.obwodKwadratu;
else
error('Cannot identify a figure.');
end
end % obwod
end % methods
methods (Access = protected, Static)
function [propertyValue, status, msgString] = ...
getPropertyValue(propertyName, inputCell)
I = strcmpi(propertyName,inputCell);
if sum(I) ~= 0
if (find(I)+1) <= length(inputCell)
propertyValue = inputCell{find(I)+1};
status = true;
msgString = 'No errors';
else
propertyValue = [];
status = false;
msgString = ['Too few arguments for ''' propertyName '''.'];
end
else
propertyValue = [];
status = false;
msgString = ['No property ' propertyName];
end
end % getPropertyValue(propertyName, cellArray)
end % methods (Access = protected, Static)
end % classdef
Just because the method is static, doesn't mean you can use it as if it were a separate function in the search path. You need to call obj.getPropertyValue or FigureObjects.getPropertyValue instead.