Showing posts with label function. Show all posts
Showing posts with label function. Show all posts

Thursday, March 22, 2012

Custom Stored procedure

Hi, I've tried to develop custom function for AS 2005, written in C#, and registered as database assembly

Code snippet is here

public string MySampleMethod()

{

AdomdCommand command = new AdomdCommand();

command.CommandText = string.Format("with member A AS 'username' select A on 0 FROM MyCube");

return (string)command.ExecuteScalar();

}

Error that I've got was "XML for Analysis parser: The input query is not in the language specified in the Dialect property for this request."

When I execute the same query from SQL Management Studio, everything works OK.

What I did wrong and how it can be resolved?

Thanks in advance

Borko

Hi Borko,

You can't use AS stored procs to execute queries on the same connection as you're using to call the proc, unfortunately. You can open a new connection within the proc but that may or may not be particularly useful to you - here's an example of how to do this:

using System;

using System.Collections.Generic;

using System.Text;

using Microsoft.AnalysisServices.AdomdServer;

using Microsoft.AnalysisServices.AdomdClient;

namespace MDXTests

{

public class RunMDXQueries

{

public static Microsoft.AnalysisServices.AdomdClient.AdomdDataReader RunAQuery()

{

Microsoft.AnalysisServices.AdomdClient.AdomdCommand c = new Microsoft.AnalysisServices.AdomdClient.AdomdCommand("select measures.members on 0 from [adventure works]");

AdomdConnection conn = new AdomdConnection(@."Data Source=localhost\sh; Provider=msolap.3; initial catalog=adventure works dw");

conn.Open();

c.Connection = conn;

return c.ExecuteReader();

}

}

}

You need to set security permissions to 'unrestricted' to get this to work; you can then call this from SQLMS using the following:

CALL SPSRUNNINGQUERIES.RUNAQUERY()

HTH,

Chris

|||

Chris,

information that is not possible to execute queries on the same connection as connection used to call the proc is very usefull.

Thank you very much.

Borko

Sunday, March 11, 2012

Custom 'Order By' Function?

Hi I have a column varchar(4). Users enter values in one of 5 formats -
1) 1,2,3,4...10,11
2) 01,02,03,04...10,11
3) A1,A2,A3,B1,B2,B3...B10,B11
4) 1.1,2.1,3.1.....10.1,11.1
5) 1.1, 1.1A, 1.1B, 2.1, 2.1A, 2.1B....10.1,10.1A
The queruies that select from this table will only select records with
one of the formats at any one time. Is it possible to ensure the order
is always logically correct based on numerical and alphabetical
ordering, as above?
So far its seems ok except formats 4 & 5 where I get the folowoing
output-
1.3 1.3A 1.3P 11.3 16.3 2.3 2.3P 2.3S
Thanks
hals_leftHi
your query will work fine if ur 4 and 5 looks similar to 2.
the results in 4 & 5 are considered and sorted as per the char value.
prefix 0 ans see the results.
--
best Regards,
Chandra
http://chanduas.blogspot.com/
http://groups.msn.com/SQLResource/
---
"hals_left" wrote:

> Hi I have a column varchar(4). Users enter values in one of 5 formats -
>
> 1) 1,2,3,4...10,11
> 2) 01,02,03,04...10,11
> 3) A1,A2,A3,B1,B2,B3...B10,B11
> 4) 1.1,2.1,3.1.....10.1,11.1
> 5) 1.1, 1.1A, 1.1B, 2.1, 2.1A, 2.1B....10.1,10.1A
> The queruies that select from this table will only select records with
> one of the formats at any one time. Is it possible to ensure the order
> is always logically correct based on numerical and alphabetical
> ordering, as above?
> So far its seems ok except formats 4 & 5 where I get the folowoing
> output-
> 1.3 1.3A 1.3P 11.3 16.3 2.3 2.3P 2.3S
> Thanks
> hals_left
>|||On 28 Jul 2005 08:00:54 -0700, hals_left wrote:

>Hi I have a column varchar(4). Users enter values in one of 5 formats -
>
>1) 1,2,3,4...10,11
>2) 01,02,03,04...10,11
>3) A1,A2,A3,B1,B2,B3...B10,B11
>4) 1.1,2.1,3.1.....10.1,11.1
>5) 1.1, 1.1A, 1.1B, 2.1, 2.1A, 2.1B....10.1,10.1A
Hi hals_left,
How does one store 10.1A in a varchar(4) column?

> is thgere now way to write a different
>ordering function?
Try the following. It's not pretty, but it might work:
ORDER BY
CASE
WHEN my_column LIKE '[A-Z]%'
THEN LEFT (my_column, 1)
END,
CASE
WHEN my_column LIKE '[A-Z]%'
THEN CAST (SUBSTRING (my_column, 2, 3) AS int)
WHEN my_column LIKE '%.%'
THEN CAST (LEFT (my_column, CHARINDEX ('.', my_column) - 1) AS int)
ELSE CAST (my_column AS int)
END,
CASE
WHEN my_column LIKE '%.%'
THEN SUBSTRING (my_column, CHARINDEX ('.', my_column) + 1, 4)
END
(untested)
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)

Thursday, March 8, 2012

Custom Grouping Problem

I am having some trouble with grouping. I have a custom function that returns the field to group on depending on the parameters provided by the user. This is not working, however if I select the same value from the grouping drop down list that is returned by the custom function the grouping works. My custom funtion is as follows:

Function OrganisationGroup() As String
Dim Group As String
Group = ""
Select Case Report.Parameters!EnterpriseOption.Value
Case "1"
Group = Group1Value()
Case "2"
Group = "DepartmentDesc"
Case "3"
Group = "OrganizationDesc"
Case "4"
Group = "OrganizationDesc"
End Select

If Group = "" Then
Return "0"
Else
Return "Fields!" & Group & ".Value"
End If
End Function

Function Group1Value() As String
Dim Group As String
Group = ""
Select Case Report.Parameters!ReportType.Value
Case "1"
Group = "StockFamilyDesc"
Case "2"
Group = "GroupDesc"
Case "3"
Group = "Saleable"
Case "4"
Group = "Saleable"
Case "5"
Group = "SaleableGLCodeDesc"
Case "6"
Group = "Saleable"
End Select
Return Group
End Function

Does anyone have any ideas on why the grouping would not be working with the custom function?

Thanks in advance.
I have solved the problem myself. The following changes to the custom code fixed the problem.

Function Group1Value() As String
Dim Group As String
Group = ""
Select Case Report.Parameters!ReportType.Value
Case "1" Group = "StockFamilyDesc"
Case "2" Group = "GroupDesc"
Case "3" Group = "Saleable"
Case "4" Group = "Saleable"
Case "5" Group = "SaleableGLCodeDesc"
Case "6" Group = "Saleable"
End Select
Return Group
End Function

Now is ...

Function Group1Value(fields As Fields) As String
Dim Group As String
Group = ""
Select Case Report.Parameters!ReportType.Value
Case "1" Group = fields!StockFamilyDesc.Value
Case "2" Group = fields!GroupDesc.Value
Case "3" Group = fields!Saleable.Value
Case "4" Group = fields!Saleable.Value
Case "5" Group = fields!SaleableGLCodeDesc.Value
Case "6" Group = fields!Saleable.Value
End Select
Return Group
End Function

Similar changes in Function OrganisationGroup()

Custom Grouping Problem

I am having some trouble with grouping. I have a custom function that returns the field to group on depending on the parameters provided by the user. This is not working, however if I select the same value from the grouping drop down list that is returned by the custom function the grouping works. My custom funtion is as follows:

Function OrganisationGroup() As String
Dim Group As String
Group = ""
Select Case Report.Parameters!EnterpriseOption.Value
Case "1"
Group = Group1Value()
Case "2"
Group = "DepartmentDesc"
Case "3"
Group = "OrganizationDesc"
Case "4"
Group = "OrganizationDesc"
End Select

If Group = "" Then
Return "0"
Else
Return "Fields!" & Group & ".Value"
End If
End Function

Function Group1Value() As String
Dim Group As String
Group = ""
Select Case Report.Parameters!ReportType.Value
Case "1"
Group = "StockFamilyDesc"
Case "2"
Group = "GroupDesc"
Case "3"
Group = "Saleable"
Case "4"
Group = "Saleable"
Case "5"
Group = "SaleableGLCodeDesc"
Case "6"
Group = "Saleable"
End Select
Return Group
End Function

Does anyone have any ideas on why the grouping would not be working with the custom function?

Thanks in advance.
I have solved the problem myself. The following changes to the custom code fixed the problem.

Function Group1Value() As String
Dim Group As String
Group = ""
Select Case Report.Parameters!ReportType.Value
Case "1" Group = "StockFamilyDesc"
Case "2" Group = "GroupDesc"
Case "3" Group = "Saleable"
Case "4" Group = "Saleable"
Case "5" Group = "SaleableGLCodeDesc"
Case "6" Group = "Saleable"
End Select
Return Group
End Function

Now is ...

Function Group1Value(fields As Fields) As String
Dim Group As String
Group = ""
Select Case Report.Parameters!ReportType.Value
Case "1" Group = fields!StockFamilyDesc.Value
Case "2" Group = fields!GroupDesc.Value
Case "3" Group = fields!Saleable.Value
Case "4" Group = fields!Saleable.Value
Case "5" Group = fields!SaleableGLCodeDesc.Value
Case "6" Group = fields!Saleable.Value
End Select
Return Group
End Function

Similar changes in Function OrganisationGroup()

Custom function with multiple variables

Hello,
I must say I am not too experienced in writing custom functions in
TSQL. Perhaps I am asking impossible
I have run into problems that the client platform is not able to
transmit the unicode characters properly, so I need a solution that
woul allow to call insert/update queries with ASCII charset only. The
current solution is that every unicode string literal is replaced with
a long sum of NCHAR(n) and string literals containing only ASCII chars.
That made me run into some wierd 'query optimisation' error.
I am now thinking maybe I could create a function where I could pass
all the unicode code values and string literals and what would
concatenate all them into one string. So, the question is -
1) Is it possible to create a function with variable number of
arguments
2) Can these arguments be of different types - mixed integer and string
3) Is TSQL strong enough to provide means of creating program that
loops over all the arguments and concatenates all of them into one
string, converting the int arguments uzing NCHAR() function.
Example:
MyFn(256,1000,'ABC',300,400,'1234')
returns ''ABC?' (The funny unicode chars replaced with ? for the
sake of example)
Thank you for any hints,
Pavils> 1) Is it possible to create a function with variable number of arguments ?
No. The number of arguments is defined when you create the function.
Even if you specify default values for some arguments, when you call
the UDF you must specify the DEFAULT keyword in the place of the values
for those arguments.

> 2) Can these arguments be of different types - mixed integer and string ?
No, but in SQL Server 2000 (or later) you can use the sql_variant
datatype, which can represent any other scalar datatype (except text,
ntext, image and timestamp).

> 3) Is TSQL strong enough to [...] ?
Maybe, but I don't think that would be a good idea.
You should think about another way of dealing with this issue.
Razvan

Custom Function in SQL Statement?

In MS Access, I could write a function in a module, then just call that function as part of the SQL statement. For example, "SELECT RemoveDashes([SS_No]) AS SSN FROM Employee" with "RemoveDashes" being the name of the function.

I'm trying to do the same with an asp.net page and sql server. I have a custom function in the code behind that I call in the SQL statement, but I get the error, "not a recognized function name".

What do I need to do to make this work?
All help is greatly appreciated!

Lynnetteasp.net and sql server are two different things...you cannot call a vb/c# function in your sql statement...you can write the function in a UDF in your sql server and call it in your sql statement.|||Thanks for your response. I am brand new to SQL Server, but not so new to asp.net. Any ideas how to modify this vb.net function to a UDF?

Thanks again for all your help!
lds

Function GetWorkStatus(ByVal sU As Object, ByVal sSG As Object) As Integer

Dim dtEdate As String = Calendar1.SelectedDate.ToShortDateString()

Dim mydateMonth As Integer = DatePart("m", dtEdate)

Dim thisDay As String = CStr(DatePart("d", dtEdate))

Dim sDayOfWeek As String = CStr(DatePart("w", dtEdate))

Dim cnn As New SqlConnection(constants.SQLConStrFLSA)

Dim cmd As New SqlCommand("usp_CheckWorkStatus", cnn)

Try

With cmd

.CommandType = CommandType.StoredProcedure

With .Parameters.Add("@.ForThisDate", SqlDbType.DateTime)

.Value = dtEdate

End With

With .Parameters.Add("@.mydateMonth", SqlDbType.Int)

.Value = mydateMonth

End With

With .Parameters.Add("@.thisDay", SqlDbType.VarChar, 2)

.Value = thisDay

End With

With .Parameters.Add("@.theUnion", SqlDbType.NVarChar, 2)

.Value = sU

'Session("sUn") = sU

End With

With .Parameters.Add("@.theSG", SqlDbType.NVarChar, 50)

.Value = sSG

'Session("strSG") = sSG

End With

End With

cnn.Open()

Dim da As New SqlDataAdapter(cmd)

Dim ds As New DataSet

da.Fill(ds, "SGDetails")

'no record in FLSAScheduleGroup

If ds.Tables("SGDetails").Rows.Count = 0 Then

Select Case sSG

Case "08"

If sDayOfWeek = 1 OrElse sDayOfWeek = 7 Then 'Sunday or Saturday

Return 0

Else

Return 1

End If

Case "09"

If sDayOfWeek = 1 OrElse sDayOfWeek = 2 Then 'Sunday or Monday

Return 0

Else

Return 1

End If

Case "12"

If sDayOfWeek = 4 OrElse sDayOfWeek = 5 Then 'Wed or Thurs

Return 0

Else

Return 1

End If

Case "13"

If sDayOfWeek = 5 OrElse sDayOfWeek = 6 Then 'Thurs or Friday

Return 0

Else

Return 1

End If

Case "14"

If sDayOfWeek = 6 OrElse sDayOfWeek = 7 Then 'Friday or Saturday

Return 0

Else

Return 1

End If

Case "31"

If sDayOfWeek = 1 Or 7 Then

Return 0

Else

Return 1

End If

Case Else

Return 1

End Select

ElseIf ds.Tables("SGDetails").Rows.Count = 1 Then 'if there is a row in FLSAScheduleGroup

Return 0

End If

Catch ex As Exception

lblError.Text = ex.ToString

Finally

With cmd.Connection

If .State = ConnectionState.Open Then

.Close()

End If

End With

Session("sUn") = Nothing

Session("strSG") = Nothing

End Try

End Function

|||what you have seems to be fine although it can be fine-tuned a little bit more..i dont see where you are calling a function in a sql stmt here..|||I wrote the function for the vb.net code behind, and called it from the <ItemTemplate Text=> part of the datagrid.

I have no idea how to make it work in SQL - don't know how to write a UDF.

Thanks again for all your help. Sorry the code is so spaced out - don't know what the "POST-ing" did to it.

Lynnette|||ok you got me confused when you said you are trying to call a function in codebehind from SQL.

what you have seems to be a regular vb function that queries a database to fill a dataset. so what are you trying to do now ? does this function not work ? do you get any errors and if so at which line ? and what is the xact error message ?|||Thanks so much for sticking with me here. I'm the only one at my office that does .NET, so I'm kind of an island here.

The vb.net Function "GetWorkStatus" in the post above works fine. I get the error, "not a recognized function name" when I try to call it from another function, that is using it in the SQL statement to identify values for the specified field. Here is the calling function:


Private Sub GetTmpRecs()
'uses the AppSettings table to generate WHERE clause from the filter values

Dim dtWdate As String = Calendar1.SelectedDate.ToShortDateString()
Dim cnn As New SqlConnection(constants.SQLConStrFLSA)
Dim wValue As String = Session("svFilterValue")
Dim dtEdate As DateTime = Now()
Dim strUser As String = Session("sUser")

Dim sSQL As String = "INSERT INTO tmpFLSAEmpInfo "
sSQL = sSQL & " (Emp_Number, PT_ID, Name_full, Division, Department, Job_Dept_Code, Dept_Mgr, "
sSQL = sSQL & " DeptInfo, Job_Supervisor, Location, Shift, sUnion, sSG, WrkDate, WrkStatus, HrsWorked, Username, AddDate) SELECT "
sSQL = sSQL & "hcsoSharedTables.dbo.Employee2.Emp_Number, "
sSQL = sSQL & "hcsoSharedTables.dbo.Employee2.[ID], "
sSQL = sSQL & "hcsoSharedTables.dbo.Employee2.Name_Full, "
sSQL = sSQL & "hcsoSharedTables.dbo.Employee2.Division, "
sSQL = sSQL & "hcsoSharedTables.dbo.Employee2.Department,"
sSQL = sSQL & "hcsoSharedTables.dbo.employee2.Job_Dept_Code, "
sSQL = sSQL & "hcsoSharedTables.dbo.employee2.Dept_Mgr, "
sSQL = sSQL & "hcsoSharedTables.dbo.employee2.Department + ' - ' + hcsosharedtables.dbo.employee2.Dept_Mgr + ' - ' + hcsosharedtables.dbo.employee2.job_dept_code, "
sSQL = sSQL & "hcsoSharedTables.dbo.Employee2.Job_Supervisor, "
sSQL = sSQL & "hcsoSharedTables.dbo.Employee2.Loc_Name, "
sSQL = sSQL & "hcsoSharedTables.dbo.Employee2.Shift, "
sSQL = sSQL & "hcsoSharedTables.dbo.Employee2.[Union], "
sSQL = sSQL & "hcsoSharedTables.dbo.Employee2.Sched_Group, "
sSQL = sSQL & "'" & dtWdate & "', "
sSQL = sSQL & "IIF(GetWorkStatus(hcsoSharedTables.dbo.Employee2.[Union], hcsoSharedTables.dbo.Employee2.Sched_Group)=0, 0,1) AS WrkStatus, "
sSQL = sSQL & "IIF(GetWorkStatus(hcsoSharedTables.dbo.Employee2.[Union], hcsoSharedTables.dbo.Employee2.Sched_Group)=0, 0,1) AS HrsWorked, "
sSQL = sSQL & "'" & strUser & "', "
sSQL = sSQL & "'" & dtEdate & "' "
'sSQL = sSQL & "INTO tmpFLSAEmpInfo "
sSQL = sSQL & "FROM hcsoSharedTables.dbo.Employee2 " & wValue & ""

Dim ds As DataSet = New DataSet
constants.ExecuteSQL(sSQL, constants.SQLConStrFLSA)

End Sub

|||So I got it right..you were indeed trying to call a vb function into an sql query..I can suggest moving the entire code into a stored proc..move all the logit into it..you can get it all done in one trip.

Wednesday, March 7, 2012

Custom Data Mining Functions

I would like to write a custom mining function, which takes a string, queries the database, and returns an answer based upon those queries. So the basic function is then:

[MiningFunction("Performs Foo")]
public string Foo(string param)
{
// process parameters
// query database

// calculate answer from query results

// return query results
}

And is executed from the client using:

SELECT Foo("X Y Z") FROM FooModel

This arrangement is so that resource-intensive calculations are performed server-side.

My question is: what is the preferrable method for executing the database query from within the custom mining function?

Custom mining functions are not actually designed for this kind of operations. They are intended for predictive features that are related to the mining model and typically this kind of operations do not need external access (such as a database query). I assume that your function's calculation part will use some information from the mining model and apply it to the database query results.

I think you should use a stored procedure. Inside the stored procedure, you should use the server side object model (add a reference to Microsoft.AnalysisServices.AdomdServer). With the server side object model, you can perform the following operations:

- use AdomdCommand to execute calls such as CALL SystemOpenQuery(DataSource, Query), which is the recommended way of querying a relational database from analysis services

- also use AdomdCommand to execute calls such as SELECT .... FROM YourModel PREDICTION JOIN OPENQUERY(DataSource, Query)

This would allow you to get the information from the data base together with scoring for each, scoring computed as a prediction from your model ). Your code could use the results and perform aggregations or more complex computations on the result.

If, in the code of your stored procedure, you need to get extra information from your model, you can traverse the content of the mining model using the object model.

The article at http://www.sqlserverdatamining.com/DMCommunity/TipsNTricks/4264.aspx contains such a stored procedure, which requires both data and model content information, so I think it may be a good example. The data is coming directly from the model, with a drillthrough query. You can replace that query with a CALL SystemOpenQuery or prediction against an OPENQUERY statement.

Hope this helps

|||Yes, this is helpful. I'm looking at the material you referenced to see if it completely answers my question. Unfortunately, I don't seem able to progress pass the logon screen at sqlserverdatamining at the moment, so I can't get the .cs example...|||Do you have an account on sqlserverdatamining.com? Do you have problems logging in with your account? Or creating a new account

Friday, February 24, 2012

Custom Code/function to format Seconds to hh:mm:ss with ability to go over 24 hours

Hello,

I am trying to get this to work - but it only returns minutes & seconds:

Function Seconds2mmss(ByVal seconds As Integer) As String
Dim ss As Integer = seconds Mod 60
Dim mm As Integer = (seconds - ss) / 60
Seconds2mmss = String.Format("{0:0}:{1:00}", mm, ss)
End Function

Can anyone help me out? I am not that familiar with VB.

Thanks,

Deb

I think this is more of an access report expression format, but it should help you out.

=Int([sumofacd]/3600) & ":" & (Int([sumofacd]/60)-(Int([sumofacd]/3600)*60)) & ":" & format(([sumofacd] Mod 60),"00")

"It works by dividing sumofacd by the number of seconds in 1 hour, the integer of this then becomes the Hours, we then need to take the remainder and convert it to Minutes.

There is more than one way to do the next part. My choice is to divide sumofacd by 60, the integer of this will be the total number of minutes from sumofacd, I then repeat the first part of the equation this time multiplying it by 60 to change it back to minutes, I then minus this from the minutes calculated earlier, this gives the minutes (ie less than 60 or 1 hour).

To get seconds is much easier, as the other elements are made up of multiples of 60 we only require the balance, below 60 so we use the VB Mod function to do this and then format the result.

My first error was to ignore the formatting, doing this would give a :3 instead of :03, and thinking about it you maybe should format the minutes the same way to give 0:03:03 instead of 0:3:03.

Think I will stop looking at the equation, can see additional brakets in the minutes calculation now, for the record would complete each part of the equation before attempting to use the format, as you need the result before formatting, this way you are less likely to get mixed up due to the high number of brackets used"

http://www.utteraccess.com/forums/showflat.php?Board=87&Number=1140884

|||

Thanks for your reply, however, I am not sure how to incorporate this into my report. Does the above expression belong in the code itself, or is it referenced in a report field? This is the first time I've ever tried to use code in a RS report, if you could steer me in the right direction I'm sure I can figure it out.

Deb

Custom Code to Setup Parameter

I have a function that calcualte last_sunday date and return a datetime.

I have two Parameter in my report

start_date

end_date

and I put th following code in the report Parameer Properties

for Start date parameter

code.Last_Sunday

For End Date Parameter

code.Last_Sunday.adddays(6)

However when I ry to Preview I am getting this error

[rsReportParameterPropertyTypeMismatch] The property ‘DefaultValue’ of report parameter ‘Start_Date’ doesn't have the expected type.

[rsReportParameterPropertyTypeMismatch] The property ‘DefaultValue’ of report parameter ‘End_Date’ doesn't have the expected type.

Build complete -- 2 errors, 0 warnings

What I am doign Wrong both parameter are defined as datetime.

Thanks

Tanweer

Public Function Last_Sunday() As datetime

Dim Processed_date As DateTime
Dim start_date As DateTime
' Dim End_date As DateTime
Processed_date = DateTime.Today

'start_date = DateAdd(Processed_date - Weekday(Processed_date) + 1)
Select Case Processed_date.DayOfWeek.ToString
Case "Monday"
start_date = Processed_date.AddDays(-8)
Case "Tuesday"
start_date = Processed_date.AddDays(-9)
Case "Wednesday"
start_date = Processed_date.AddDays(-10)
Case "Thursday"
start_date = Processed_date.AddDays(-11)
Case "Friday"
start_date = Processed_date.AddDays(-12)
Case "Saturday"
start_date = Processed_date.AddDays(-13)
Case "Sunday"
start_date = Processed_date.AddDays(-14)
End Select
' End_date = format(start_date.AddDays(6),"mm/dd/yyyy")
console.writeline (start_date)
Return format(start_date,"MM/dd/yyyy")
End Function

You may want to try changing this line:

Return format(start_date,"MM/dd/yyyy")

to

CDate(Return format(start_date,"MM/dd/yyyy"))

The format function returns a string - not a DateTime...

Why are you formatting it here?

You mention a report...would it not be better to just pass the unformatted datetime to your report and handle the formatting in the report?

If you want create a re-usable function like this, it is better to return the raw data and handle formatting etc from where it is called. It is more generic and re-useable that way.

Steve

Custom Code problem!

Hi,
I want to use Custom Code to control the Visibility of a Group.
I write a test code, it always Return True:
Function CanSeen() as Boolean
Return True
End Function
Then I set the initial visibility of a group to Expression =Code.CanSeen()
But the the group can't seen!!
What is the problem?Are you calling your custom code from the row properties? If so, which
property? The "hidden" one? If so, notice that RS is asking you "do you want
this row to be hidden?" and you're saying "True". Perhaps that's the point.
I hope this helps
--
Please mark the correct/helpful answers!
"ad" wrote:
> Hi,
> I want to use Custom Code to control the Visibility of a Group.
> I write a test code, it always Return True:
> Function CanSeen() as Boolean
> Return True
> End Function
> Then I set the initial visibility of a group to Expression =Code.CanSeen()
> But the the group can't seen!!
> What is the problem?
>
>
>

Custom Code problem

I have this very basic custom code in my report:
Public Shared Function Basis(byVal Value as Integer) As Double
Basis = Basis + value
End Function
When I call this code, using =Code.Basis(Fields!BWT.Value), I expect it to
be like a running total. But all I get back is whatever the value of
Fields!BWT.Value is, without it adding up. I know that I could use the
runningvalue function, but I am wondering why this code doesn't work?quite possible the value of the function is not static. So everytime you come
into the function the value is reset. Try setting a temp invisible textbox to
basis' value evertime it updates.
"dachrist" wrote:
> I have this very basic custom code in my report:
> Public Shared Function Basis(byVal Value as Integer) As Double
> Basis = Basis + value
> End Function
> When I call this code, using =Code.Basis(Fields!BWT.Value), I expect it to
> be like a running total. But all I get back is whatever the value of
> Fields!BWT.Value is, without it adding up. I know that I could use the
> runningvalue function, but I am wondering why this code doesn't work?

Custom Code in Chart - background color

I have the following very simple code block that I wrote for a chart.
public function bdr_chartcolor(xType as string) as string
IF xType = "IR"
return "White"
ELSE
return "Blue"
END IF
end function
HOW and WHERE do I implement it to set the charts background color? Many
properties of objects have EXPRESSION as an option, HOWEVER, there is no
EXPRESSION as a type for a chart's background color in the properties.Chart area, Fill.
"MSSQLServerDeveloper" <MSSQLServerDeveloper@.discussions.microsoft.com>
wrote in message news:22B72235-5282-4095-951F-9B9DCF89E0B3@.microsoft.com...
>I have the following very simple code block that I wrote for a chart.
> public function bdr_chartcolor(xType as string) as string
> IF xType = "IR"
> return "White"
> ELSE
> return "Blue"
> END IF
> end function
> HOW and WHERE do I implement it to set the charts background color? Many
> properties of objects have EXPRESSION as an option, HOWEVER, there is no
> EXPRESSION as a type for a chart's background color in the properties.|||Sorry,
plot area, fill.
There are two, the area outside the chart plot area and the area inside the
chart plot area.
Use Code.bdf_chartcolor(...) in the expression editor.
"MSSQLServerDeveloper" <MSSQLServerDeveloper@.discussions.microsoft.com>
wrote in message news:22B72235-5282-4095-951F-9B9DCF89E0B3@.microsoft.com...
>I have the following very simple code block that I wrote for a chart.
> public function bdr_chartcolor(xType as string) as string
> IF xType = "IR"
> return "White"
> ELSE
> return "Blue"
> END IF
> end function
> HOW and WHERE do I implement it to set the charts background color? Many
> properties of objects have EXPRESSION as an option, HOWEVER, there is no
> EXPRESSION as a type for a chart's background color in the properties.

Custom Code error with VB function

Hello, I am about out of hair from pulling it out. If someone could please show me what I'm doing wrong I would really appreciate it. I have this function for a SSRS 2005 report:

Public Function funAdditions(pFields As Fields) As Double
if pFields !FA00902_AMOUNT.Value > 0 and
pFields !FA00902_TRANSACCTTYPE.Value = 3 and
pFields !FA00902_DEPRTODATE.Value > Parameters!BeginDate.Value and
pFields !FA00902_DEPRTODATE.Value <= Parameters!CutOffDate.Value and NOT
instr(pFields !FA00902_SOURCDOC.Value, "FACHG")=1
then return pFields !FA00902_AMOUNT.Value
end
else if pFields !FA00902_TRANSACCTTYPE.Value = 3 and
pFields !FA00902_DEPRTODATE.Value > Parameters!BeginDate.Value and
pFields !FA00902_DEPRTODATE.Value <= Parameters!CutOffDate.Value and
instr(pFields !FA00902_SOURCDOC.Value, "FACHG")=1
then return pFields !FA00902_AMOUNT.Value
end
End Function

...and after much research cannot figure out the solution to this error:

[rsCompilerErrorInCode] There is an error on line 1 of custom code: [BC30201] Expression expected.

I'm new to SSRS so is there a syntax error I'm missing?

Thanks in advance,

Buster

Just a thought, and it may be that your code has been munged by pasting it into here, but you seem to have your code lines split over several physical lines, to do that in VB and VBScript you need to use the line continuation character, which is an underscore. So your first line should look something like this:

Public Function funAdditions(pFields As Fields) As Double
if pFields !FA00902_AMOUNT.Value > 0 and _
pFields !FA00902_TRANSACCTTYPE.Value = 3 and _
pFields !FA00902_DEPRTODATE.Value > Parameters!BeginDate.Value and _
pFields !FA00902_DEPRTODATE.Value <= Parameters!CutOffDate.Value and NOT _
instr(pFields !FA00902_SOURCDOC.Value, "FACHG")=1 then

return pFields !FA00902_AMOUNT.Value

...etc...

Sometimes it can be handy to fire up the macro code editor that you get with Excel and Word and do your code in that to make sure it is syntactically correct.

Custom Code Error

I'm receiving an #ERROR where I've call a function created in the custom code section. The reports works fine in development debug mode, only errors after deploying to SSRS. Note the custom code contain code that access the database using the SYSTEMS.DATA.SQLCLIENT namespace classes. Is there a security access problem in SSRS reports server?I had the same problem..
I've created a custom assembly for that..

Imports System.Data.OracleClient
Imports System.IO

'Important to get it work within a report
<Assembly: System.Security.AllowPartiallyTrustedCallers()>

Public Class DB

'Write do Database
Public Shared Function writeBack(ByVal FehlerID As Integer) As String
Dim perm As New OraclePermission(Security.Permissions.PermissionState.Unrestricted)
perm.Assert()

Dim conn As New OracleConnection
conn.ConnectionString = "Data Source=DB;Unicode=True;user=scott;password=tiger;"
conn.Open()
Dim oracleCommand1 As New System.Data.OracleClient.OracleCommand
oracleCommand1.Connection = conn
oracleCommand1.CommandText = "update ben_mailversand set gesendet=1 where fehlerid=" & FehlerID
oracleCommand1.ExecuteScalar()
conn.Close()
writeBack = oracleCommand1.CommandText
End Function
End Class

Thats not exactly brilliant but I found no other way..

in rspolicy.conf you have to set this assembly to fulltrust..
|||

There is a reason why you will need to assert FullTrust permissions in the OracleClient case: If you read the MSDN documentation for the OraclePermission class and the SqlClientPermission class and compare them, you will notice the following statement:
"This class [i.e. OraclePermission] is intended for future use when the .NET
Framework Data Provider for Oracle is enabled for partial trust scenarios.
The provider currently requires FullTrust permission."
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemdataoracleclientoraclepermissionclasstopic.asp

Note: The managed provider for SQL Server is enabled for partial trust scenarios, therefore it
is sufficient (and advisable) to just assert the SqlClientPermission when using it in custom assemblies.

-- Robert

|||

Thanks for your post, it led me in the right direction. I struggled for awhile but I've finally gotten it to work.

These are the items that took me awhile to figure out:

1. Placement of custom assemby on ReportsServer:

Must be placed in this directory "prior" to deploying report.

C:\Program Files\Microsoft SQL Server\MSSQL.3\Reporting Services\ReportServer\bin

2. rssrpolicy.config FullTrust entry:

There are two way to enter this for signed or unsigned assemblies, you need to enter the correct method.

Thanks again,

Mike

Custom code changes don't "take"

I am having a problem when I add a function to the Code window it
isn't recognized. When I do a compile I get an error because the
expression doesn't 'see' the new function.
I have closed the .rdl, I have closed down Visual Studio. Has anyone
else run into this problem?
Thanks in advance.
PattiAre you getting error messages? If so, what? Have you tested the code?
daw
"patti" wrote:
> I am having a problem when I add a function to the Code window it
> isn't recognized. When I do a compile I get an error because the
> expression doesn't 'see' the new function.
> I have closed the .rdl, I have closed down Visual Studio. Has anyone
> else run into this problem?
> Thanks in advance.
> Patti
>

Custom Code Access Error

I've created a function Period in custom code block. Then I put expression
=Code!Period()
in the textbox. Then I got this message:
The value expression for the textbox â'textbox6â' contains an error: [BC30367]
Class 'ReportExprHostImpl.CustomCodeProxy' cannot be indexed because it has
no default property.
Am I doing something wrong?
--
Thanks in advance,
IDcode.period not code!period
--
Bruce Loehle-Conger
MVP SQL Server Reporting Services
"exkievan" <exkievan@.discussions.microsoft.com> wrote in message
news:58940691-9E20-49AE-82E8-4F8BE0092E9C@.microsoft.com...
> I've created a function Period in custom code block. Then I put expression
> =Code!Period()
> in the textbox. Then I got this message:
> The value expression for the textbox 'textbox6' contains an error:
[BC30367]
> Class 'ReportExprHostImpl.CustomCodeProxy' cannot be indexed because it
has
> no default property.
> Am I doing something wrong?
> --
> Thanks in advance,
> ID

Custom Code - Reference Report Objects

Hi,
Can anyone point me in the right direction on how to reference report objects in a custom sub or function. For example if I want to assign a value to a report parameter or a textbox
public Sub SetDepth()
Parameters!test.Value = 2
ReportItems!Textbox23.value = "test"
end sub
I've tried really simle stuff like below but i get the following error [BC30469] Reference to a non-shared member requires an object reference.
Cheers
KevinYou can pass in the Parameters or ReportItems collection as an argument to
your function. Note you can't change the values of parameters/textboxes
though - they are read-only.
Fang Wang (MSFT)
Microsoft SQL Server Reporting Services
This posting is provided "AS IS" with no warranties, and confers no rights.
"Kevin Wilson" <KevinWilson@.discussions.microsoft.com> wrote in message
news:E136C0ED-9890-4315-8455-14687D66FB24@.microsoft.com...
> Hi,
> Can anyone point me in the right direction on how to reference report
objects in a custom sub or function. For example if I want to assign a value
to a report parameter or a textbox
> public Sub SetDepth()
> Parameters!test.Value = 2
> ReportItems!Textbox23.value = "test"
> end sub
> I've tried really simle stuff like below but i get the following error
[BC30469] Reference to a non-shared member requires an object reference.
> Cheers
> Kevin|||How do you do this?
"Fang Wang (MSFT)" wrote:
> You can pass in the Parameters or ReportItems collection as an argument to
> your function. Note you can't change the values of parameters/textboxes
> though - they are read-only.
> Fang Wang (MSFT)
> Microsoft SQL Server Reporting Services
> This posting is provided "AS IS" with no warranties, and confers no rights.
> "Kevin Wilson" <KevinWilson@.discussions.microsoft.com> wrote in message
> news:E136C0ED-9890-4315-8455-14687D66FB24@.microsoft.com...
> > Hi,
> > Can anyone point me in the right direction on how to reference report
> objects in a custom sub or function. For example if I want to assign a value
> to a report parameter or a textbox
> >
> > public Sub SetDepth()
> > Parameters!test.Value = 2
> > ReportItems!Textbox23.value = "test"
> > end sub
> >
> > I've tried really simle stuff like below but i get the following error
> [BC30469] Reference to a non-shared member requires an object reference.
> >
> > Cheers
> > Kevin
>
>|||For example if you want to calculate average sales. You have two fields
Number of Units and Sales in dollars.
You can write custom code as below:
Public Function GetAvg(ByVal NoOfUnits As Integer, ByVal TotalSales As
Decimal) As Decimal
Dim ReturnValue As Decimal
ReturnValue = 0
If NoOfUnits <> 0 Then
ReturnValue = TotalSales/NoOfUnits
End If
Return ReturnValue
End
In your table cell you can write expression as:
Code.GetAvg(Fields!Units.Value, Fields!Sales.Value)
When you preview the report, you will see the calculated average value in
that cell.
I hope this helps.
"Tanya" <Tanya@.discussions.microsoft.com> wrote in message
news:68055C09-D38E-4CDA-990C-CD4641594E33@.microsoft.com...
> How do you do this?
> "Fang Wang (MSFT)" wrote:
>> You can pass in the Parameters or ReportItems collection as an argument
>> to
>> your function. Note you can't change the values of parameters/textboxes
>> though - they are read-only.
>> Fang Wang (MSFT)
>> Microsoft SQL Server Reporting Services
>> This posting is provided "AS IS" with no warranties, and confers no
>> rights.
>> "Kevin Wilson" <KevinWilson@.discussions.microsoft.com> wrote in message
>> news:E136C0ED-9890-4315-8455-14687D66FB24@.microsoft.com...
>> > Hi,
>> > Can anyone point me in the right direction on how to reference report
>> objects in a custom sub or function. For example if I want to assign a
>> value
>> to a report parameter or a textbox
>> >
>> > public Sub SetDepth()
>> > Parameters!test.Value = 2
>> > ReportItems!Textbox23.value = "test"
>> > end sub
>> >
>> > I've tried really simle stuff like below but i get the following error
>> [BC30469] Reference to a non-shared member requires an object reference.
>> >
>> > Cheers
>> > Kevin
>>

Custom Code

I've created a function in the code tab but when I go back to the text box
that is going to call the custom code through the expression... i type code.
and my function isn't there... anybody else see this?Hi,
"Code" or "Report" is a global object pertaining to Reporting Services.
User defined functions wont be visible since it is not a user created class.
Amarnath
"gdjoshua" wrote:
> I've created a function in the code tab but when I go back to the text box
> that is going to call the custom code through the expression... i type code.
> and my function isn't there... anybody else see this?

Custom Code

Hi,

Wrote a Custom Code i.e. a function.
Can not refer to this function from an expression area. It says unrecognized identifier.

Public Function TaxDeductions(ByVal Amount As Double) As Double
TaxDeductions = Amount * .25 + Amount * 0.05
End Functrion

Code.TaxDeductions(Sum(Fields!LineAmount.Value)

Any thoughts please?

make it static i.e. Public Shared Function....

Custom Class for Function

I have several fuctions that I would like to share between my different script tasks in my SSIS package. I assume I do this by creating a custom class, but I cant quite figure it out. Can someone please point me in the right direction?

Thank You!!

Check Books Online under Programming Integration Services.|||

I didn't see any instruction for how to do this in the Books Online. If it is there, I can't find it. Please help, I would like to figure out how to do this.

Thank You.

|||

AspUser123 wrote:

I didn't see any instruction for how to do this in the Books Online. If it is there, I can't find it. Please help, I would like to figure out how to do this.

Thank You.

Assuming you know how to create an assembly, this explains how you can reference it from your SSIS scripts.

http://msdn2.microsoft.com/en-US/library/ms136007.aspx