Search Results

Search found 74 results on 3 pages for 'directcast'.

Page 1/3 | 1 2 3  | Next Page >

  • C#'s equivalent to VB.Net's DirectCast?

    - by Collin Sauve
    This has probably been asked before, but if it has, I can't find it. Does C# have an equivalent to VB.Net's DirectCast? I am aware that it has () casts and the 'as' keyword, but those line up to CType and TryCast. To be clear, these keywords do the following; CType/() casts: If it is already the correct type, cast it, otherwise look for a type converter and invoke it. If no type converter is found, throw an InvalidCastException. TryCast/"as" keyword: If it is the correct type, cast it, otherwise return null. DirectCast: If it is the correct type, cast it, otherwise throw an InvalidCastException. EDIT: After I have spelled out the above, some people have still responded that () is equivalent, so I will expand further upon why this is not true. DirectCast only allows for either Narrowing or Widening conversions on inheritance tree, it does not support conversions across different branches like () does. ie: C#, this compiles and runs: //This code uses a type converter to go across an inheritance tree double d = 10; int i = (int)d; VB.Net, this does NOT COMPILE 'Direct cast can only go up or down a branch, never across to a different one. Dim d as Double= 10 Dim i as Integer = DirectCast(d, Integer) The equivalent in VB.Net to my C# code is CType: 'This compiles and runs Dim d as Double= 10 Dim i as Integer = CType(d, Integer) (Edit again, I was originally using strings, I changed it to double... sorry)

    Read the article

  • Casting DataTypes with DirectCast, CType, TryCast

    - by Alex Essilfie
    Ever since I moved from VB6 to VB.NET somewhere in 2005, I've been using CType to do casting from one data type to another. I do this because it is simply faster, used to exist in VB6 and I do not know why I have to be using DirectCast if there is apparently no difference between them. I use TryCast once in a while because I understand that sometimes casting can fail. I however cannot get the difference between CType and DirectCast. Can anyone tell me the difference in plain simple English what the difference the two (CType and DirectCast)? Adding examples of where to use what as well would be helpful. Thanks.

    Read the article

  • Difference between DirectCast() and CType() in VB.Net

    - by Chapso
    I am an experienced C/C++/C# programmer who has just gotten into VB.NET. I generally use CType (and CInt, CBool, CStr) for casts because it is less characters and was the first way of casting which I was exposed to, but I am aware of DirectCast and TryCast as well. Simply, are there any differences (effect of cast, performance, etc.) between DirectCast and CType? I understand the idea of TryCast.

    Read the article

  • VB .NET DirectCast and Type Reflection

    - by msarchet
    The application that I am working on has a generic Parent Form called RSChild, that is used to perform some operations depending on whether or not the control that is contained within it is in a MdiTabManager or inside of its own modal form. Then the actual User Controls contained within Inherit from a Interface Called ObjectEdit (Objects that we allow to be edited). At a point in my code I am doing this. Public Function doesTabExist(ByVal id As Integer, ByVal recordType As Enums.eRecordType) As Boolean Dim alikePages As Object = (From tabs In DirectCast(Control.FromHandle(MainForm.SharedHandle), MainForm).XtraTabbedMdiManager1.Pages Where DirectCast(tabs.MdiChild, RSChild).RSObject.RecordType = recordType Select tabs) For Each page As DevExpress.XtraTabbedMdi.XtraMdiTabPage In alikePages Select Case recordType Case Enums.eRecordType.Doctor If id = DirectCast(castTabPageToRSChild(page).RSObject, UI.Doctor).ID Then pageToActive(page) Return True End If 'rest of the cases so the case block is repeated 10 times' End Function And my castTabPageToRSChild(page) is a lambda function as Such Dim castTabPageToRSChild As Func(Of DevExpress.XtraTabbedMdi.XtraMdiTabPage, RSChild) = Function(page) DirectCast(page.MdiChild, RSChild) So my Question is, I have about 10 case statements, all because I can't seem to find a way to use reflection to get the underlying Type of the RSObject Object. So I have the whole If block repeated over and over. I tried doing castTabPageToRSChild(page)RSObject.GetType and using that in the DirectCast and I also tried creating another object that was separate from that and doing the same thing. My code works as intended I'm just trying to see if there is a manner in which I didn't have a lot of replicated code. My vision would be to do something like For Each page As XtraMdiTabPage In alikePages If id = DirectCast(castTabPageToRSchild(page).RSObject, TypeOfThatObject).Id Then Return True Next However I have a feeling this is not possible due to the behavior of DirectCast.

    Read the article

  • How to get Resharper to show a Refactoring that it already has.

    - by AngryHacker
    Whenever Resharper encounters code like this: (treeListNode.Tag as GridLine).AdvertiserSeparation = 5; it presents you with a possible fix (since treeListNode.Tag as GridLine might be null). It says: 'Replace with Direct Cast', which turns the code into the following: ((GridLine) treeListNode.Tag).AdvertiserSeparation = 5; This is great. However, when it encounters code like this: GridLine line = treeListNode.Tag as GridLine; line.AdvertiserSeparation = 5; Resharper simply displays a warning 'Possible System.NullReferenceException', but does not offer me to 'Replace with Direct Cast'. Is there a way to make Resharper offer me this refactoring, since it already has it?

    Read the article

  • How to get record value from LinqDataSource via Code Behind

    - by rockinthesixstring
    I've got a LinqDataSource that retrieves a single record. Protected Sub LinqDataSource1_Selecting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.LinqDataSourceSelectEventArgs) Handles LinqDataSource1.Selecting Dim BizForSaleDC As New DAL.BizForSaleDataContext e.Result = BizForSaleDC.bt_BizForSale_GetByID(e.WhereParameters("ID")).FirstOrDefault End Sub I'd like to be able to retrieve the values of said DataSource using the Page_Load function. Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load 'Get the right usercontrol' Dim ctrl As UserControl Select Case DataBinder.Eval(LINQDATASOURCE_SOMETHING.DataItem, "AdType") Case 1 : ctrl = DirectCast(Me.FindControl("Default1"), UserControl) Case 2 : ctrl = DirectCast(Me.FindControl("Default1"), UserControl) Case 3 : ctrl = DirectCast(Me.FindControl("ValuPro1"), UserControl) Case 4 : ctrl = DirectCast(Me.FindControl("ValuPro1"), UserControl) Case Else : ctrl = Nothing End Select 'set the control to visible' ctrl.Visible = True End Sub But obviously the code above doesn't work... I'm just wondering if there's a way to make it work. Here is the full markup <body> <form id="form1" runat="server"> <asp:LinqDataSource ID="LinqDataSource1" runat="server"> <WhereParameters> <asp:QueryStringParameter ConvertEmptyStringToNull="true" Name="ID" QueryStringField="ID" Type="Int32" /> </WhereParameters> </asp:LinqDataSource> <uc:Default ID="Default1" runat="server" Visible="false" /> <uc:ValuPro ID="ValuPro1" runat="server" Visible="false" /> </form> </body> </html> Basically what happens is the appropriate usercontrol is enabled and that usercontrol inherits the LinqDataSource and displays the appropriate information. EDIT: It's working now with the code below, however, since I'm really not into hitting the database multiple times for the same info, I'd prefer to get the value from the DataSource. 'Query the database' Dim _ID As Integer = Convert.ToInt32(Request.QueryString("ID")) Dim BizForSaleDC As New BizForSaleDataContext Dim results = BizForSaleDC.bt_BizForSale_GetByID(_ID).FirstOrDefault 'Get the right usercontrol' Dim ctrl As UserControl Select Case results.AdType Case 1 : ctrl = DirectCast(Me.FindControl("Default1"), UserControl) Case 2 : ctrl = DirectCast(Me.FindControl("Default1"), UserControl) Case 3 : ctrl = DirectCast(Me.FindControl("ValuPro1"), UserControl) Case 4 : ctrl = DirectCast(Me.FindControl("ValuPro1"), UserControl) Case Else : ctrl = Nothing End Select

    Read the article

  • Trabajando el redireccionamiento de usuarios/Working with user redirect methods

    - by Jason Ulloa
    La protección de las aplicaciones es un elemento que no se puede dejar por fuera cuando se elabora un sistema. Cada parte o elemento de código que protege nuetra aplicación debe ser cuidadosamente seleccionado y elaborado. Una de las cosas comunes con las que nos topamos en asp.net cuando deseamos trabajar con usuarios, es con la necesidad de poder redireccionarlos a los distintos elementos o páginas dependiendo del rol. Pues precisamente eso es lo que haremos, vamos a trabajar con el Web.config de nuestra aplicación y le añadiremos unas pequeñas líneas de código para lograr dar un poco mas de seguridad al sistema y sobre todo lograr el redireccionamiento. Así que veamos como logramos lo deseado: Como bien sabemos el web.config nos permite manejar muchos elementos dentro de asp.net, muchos de ellos relacionados con la seguridad, asi como tambien nos brinda la posibilidad de poder personalizar los elementos para poder adaptarlo a nuestras necesidades. Así que, basandonos en el principio de que podemos personalizar el web.config, entonces crearemos una sección personalizada, que será la que utilicemos para manejar el redireccionamiento: Nuestro primer paso será ir a nuestro web.config y buscamos las siguientes líneas: <configuration>     <configSections>  </sectionGroup>             </sectionGroup>         </sectionGroup> Y luego de ellas definiremos una nueva sección  <section name="loginRedirectByRole" type="crabit.LoginRedirectByRoleSection" allowLocation="true" allowDefinition="Everywhere" /> El section name corresponde al nombre de nuestra nueva sección Type corresponde al nombre de la clase (que pronto realizaremos) y que será la encargada del Redirect Como estamos trabajando dentro de la seccion de configuración una vez definidad nuestra sección personalizada debemos cerrar esta sección  </configSections> Por lo que nuestro web.config debería lucir de la siguiente forma <configuration>     <configSections>  </sectionGroup>             </sectionGroup>         </sectionGroup> <section name="loginRedirectByRole" type="crabit.LoginRedirectByRoleSection" allowLocation="true" allowDefinition="Everywhere" /> </configSections> Anteriormente definimos nuestra sección, pero esta sería totalmente inútil sin el Metodo que le da vida. En nuestro caso el metodo loginRedirectByRole, este metodo lo definiremos luego del </configSections> último que cerramos: <loginRedirectByRole>     <roleRedirects>       <add role="Administrador" url="~/Admin/Default.aspx" />       <add role="User" url="~/User/Default.aspx" />     </roleRedirects>   </loginRedirectByRole> Como vemos, dentro de nuestro metodo LoginRedirectByRole tenemos el elemento add role. Este elemento será el que posteriormente le indicará a la aplicación hacia donde irá el usuario cuando realice un login correcto. Así que, veamos un poco esta configuración: add role="Administrador" corresponde al nombre del Role que tenemos definidio, pueden existir tantos elementos add role como tengamos definidos en nuestra aplicación. El elemento URL indica la ruta o página a la que será dirigido un usuario una vez logueado y dentro de la aplicación. Como vemos estamos utilizando el ~ para indicar que es una ruta relativa. Con esto hemos terminado la configuración de nuestro web.config, ahora veamos a fondo el código que se encargará de leer estos elementos y de utilziarlos: Para nuestro ejemplo, crearemos una nueva clase denominada LoginRedirectByRoleSection, recordemos que esta clase es la que llamamos en el elemento TYPE definido en la sección de nuestro web.config. Una vez creada la clase, definiremos algunas propiedades, pero antes de ello le indicaremos a nuestra clase que debe heredar de configurationSection, esto para poder obtener los elementos del web.config.  Inherits ConfigurationSection Ahora nuestra primer propiedad   <ConfigurationProperty("roleRedirects")> _         Public Property RoleRedirects() As RoleRedirectCollection             Get                 Return DirectCast(Me("roleRedirects"), RoleRedirectCollection)             End Get             Set(ByVal value As RoleRedirectCollection)                 Me("roleRedirects") = value             End Set         End Property     End Class Esta propiedad será la encargada de obtener todos los roles que definimos en la metodo personalizado de nuestro web.config Nuestro segundo paso será crear una segunda clase (en la misma clase LoginRedirectByRoleSection) a esta clase la llamaremos RoleRedirectCollection y la heredaremos de ConfigurationElementCollection y definiremos lo siguiente Public Class RoleRedirectCollection         Inherits ConfigurationElementCollection         Default Public ReadOnly Property Item(ByVal index As Integer) As RoleRedirect             Get                 Return DirectCast(BaseGet(index), RoleRedirect)             End Get         End Property         Default Public ReadOnly Property Item(ByVal key As Object) As RoleRedirect             Get                 Return DirectCast(BaseGet(key), RoleRedirect)             End Get         End Property         Protected Overrides Function CreateNewElement() As ConfigurationElement             Return New RoleRedirect()         End Function         Protected Overrides Function GetElementKey(ByVal element As ConfigurationElement) As Object             Return DirectCast(element, RoleRedirect).Role         End Function     End Class Nuevamente crearemos otra clase esta vez llamada RoleRedirect y en este caso la heredaremos de ConfigurationElement. Nuestra nueva clase debería lucir así: Public Class RoleRedirect         Inherits ConfigurationElement         <ConfigurationProperty("role", IsRequired:=True)> _         Public Property Role() As String             Get                 Return DirectCast(Me("role"), String)             End Get             Set(ByVal value As String)                 Me("role") = value             End Set         End Property         <ConfigurationProperty("url", IsRequired:=True)> _         Public Property Url() As String             Get                 Return DirectCast(Me("url"), String)             End Get             Set(ByVal value As String)                 Me("url") = value             End Set         End Property     End Class Una vez que nuestra clase madre esta lista, lo unico que nos queda es un poc de codigo en la pagina de login de nuestro sistema (por supuesto, asumo que estan utilizando  los controles de login que por defecto tiene asp.net). Acá definiremos nuestros dos últimos metodos  Protected Sub ctllogin_LoggedIn(ByVal sender As Object, ByVal e As System.EventArgs) Handles ctllogin.LoggedIn         RedirectLogin(ctllogin.UserName)     End Sub El procedimiento loggeding es parte del control login de asp.net y se desencadena en el momento en que el usuario hace loguin correctametne en nuestra aplicación Este evento desencadenará el siguiente procedimiento para redireccionar.     Private Sub RedirectLogin(ByVal username As String)         Dim roleRedirectSection As crabit.LoginRedirectByRoleSection = DirectCast(ConfigurationManager.GetSection("loginRedirectByRole"), crabit.LoginRedirectByRoleSection)         For Each roleRedirect As crabit.RoleRedirect In roleRedirectSection.RoleRedirects             If Roles.IsUserInRole(username, roleRedirect.Role) Then                 Response.Redirect(roleRedirect.Url)             End If         Next     End Sub   Con esto, nuestra aplicación debería ser capaz de redireccionar sin problemas y manejar los roles.  Además, tambien recordar que nuestro ejemplo se basa en la utilización del esquema de bases de datos que por defecto nos proporcionada asp.net.

    Read the article

  • Raising event in custom control.

    - by SeSSiZ
    Hi all, I'm writing a custom textblock control thats populate hyperlinks and raises event when clicked to hyperlink. I wrote this code but I got stucked. My code is : Imports System.Text.RegularExpressions Public Class CustomTextBlock Inherits TextBlock Public Event Klik As EventHandler(Of EventArgs) Public ReadOnly InlineCollectionProperty As DependencyProperty = DependencyProperty.Register("InlineCollection", GetType(String), GetType(CustomTextBlock), New PropertyMetadata(New PropertyChangedCallback(AddressOf CustomTextBlock.InlineChanged))) Private Shared Sub InlineChanged(ByVal sender As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs) DirectCast(sender, CustomTextBlock).Inlines.Clear() Dim kelimeler = Split(e.NewValue, " ") For i = 0 To kelimeler.Length - 1 If Regex.Match(kelimeler(i), "(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?").Success Then Dim x = New Hyperlink(New Run(kelimeler(i))) x.AddHandler(Hyperlink.ClickEvent, New RoutedEventHandler(AddressOf t_Click)) x.ToolTip = kelimeler(i) x.Tag = kelimeler(i) DirectCast(sender, CustomTextBlock).Inlines.Add(x) If Not i = kelimeler.Length Then DirectCast(sender, CustomTextBlock).Inlines.Add(" ") Else DirectCast(sender, CustomTextBlock).Inlines.Add(kelimeler(i)) If Not i = kelimeler.Length Then DirectCast(sender, CustomTextBlock).Inlines.Add(" ") End If ''//Console.WriteLine(kelime(i).ToString.StartsWith("@")) Next kelimeler = Nothing End Sub Public Property InlineCollection As String Get Return DirectCast(GetValue(InlineCollectionProperty), String) End Get Set(ByVal value As String) SetValue(InlineCollectionProperty, value) End Set End Property Private Shared Sub t_Click(ByVal sender As Hyperlink, ByVal e As System.Windows.RoutedEventArgs) e.Handled = True RaiseEvent Klik(sender, EventArgs.Empty) End Sub End Class This code gives error at RaiseEvent Klik(sender, EventArgs.Empty) Error is : Cannot refer to an instance member of a class from within a shared method or shared member initializer without an expliticit instance of the class. Thanks for your answers, Alper

    Read the article

  • A Nondeterministic Engine written in VB.NET 2010

    - by neil chen
    When I'm reading SICP (Structure and Interpretation of Computer Programs) recently, I'm very interested in the concept of an "Nondeterministic Algorithm". According to wikipedia:  In computer science, a nondeterministic algorithm is an algorithm with one or more choice points where multiple different continuations are possible, without any specification of which one will be taken. For example, here is an puzzle came from the SICP: Baker, Cooper, Fletcher, Miller, and Smith live on different floors of an apartment housethat contains only five floors. Baker does not live on the top floor. Cooper does not live onthe bottom floor. Fletcher does not live on either the top or the bottom floor. Miller lives ona higher floor than does Cooper. Smith does not live on a floor adjacent to Fletcher's.Fletcher does not live on a floor adjacent to Cooper's. Where does everyone live? After reading this I decided to build a simple nondeterministic calculation engine with .NET. The rough idea is that we can use an iterator to track each set of possible values of the parameters, and then we implement some logic inside the engine to automate the statemachine, so that we can try one combination of the values, then test it, and then move to the next. We also used a backtracking algorithm to go back when we are running out of choices at some point. Following is the core code of the engine itself: Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--Public Class NonDeterministicEngine Private _paramDict As New List(Of Tuple(Of String, IEnumerator)) 'Private _predicateDict As New List(Of Tuple(Of Func(Of Object, Boolean), IEnumerable(Of String))) Private _predicateDict As New List(Of Tuple(Of Object, IList(Of String))) Public Sub AddParam(ByVal name As String, ByVal values As IEnumerable) _paramDict.Add(New Tuple(Of String, IEnumerator)(name, values.GetEnumerator())) End Sub Public Sub AddRequire(ByVal predicate As Func(Of Object, Boolean), ByVal paramNames As IList(Of String)) CheckParamCount(1, paramNames) _predicateDict.Add(New Tuple(Of Object, IList(Of String))(predicate, paramNames)) End Sub Public Sub AddRequire(ByVal predicate As Func(Of Object, Object, Boolean), ByVal paramNames As IList(Of String)) CheckParamCount(2, paramNames) _predicateDict.Add(New Tuple(Of Object, IList(Of String))(predicate, paramNames)) End Sub Public Sub AddRequire(ByVal predicate As Func(Of Object, Object, Object, Boolean), ByVal paramNames As IList(Of String)) CheckParamCount(3, paramNames) _predicateDict.Add(New Tuple(Of Object, IList(Of String))(predicate, paramNames)) End Sub Public Sub AddRequire(ByVal predicate As Func(Of Object, Object, Object, Object, Boolean), ByVal paramNames As IList(Of String)) CheckParamCount(4, paramNames) _predicateDict.Add(New Tuple(Of Object, IList(Of String))(predicate, paramNames)) End Sub Public Sub AddRequire(ByVal predicate As Func(Of Object, Object, Object, Object, Object, Boolean), ByVal paramNames As IList(Of String)) CheckParamCount(5, paramNames) _predicateDict.Add(New Tuple(Of Object, IList(Of String))(predicate, paramNames)) End Sub Public Sub AddRequire(ByVal predicate As Func(Of Object, Object, Object, Object, Object, Object, Boolean), ByVal paramNames As IList(Of String)) CheckParamCount(6, paramNames) _predicateDict.Add(New Tuple(Of Object, IList(Of String))(predicate, paramNames)) End Sub Public Sub AddRequire(ByVal predicate As Func(Of Object, Object, Object, Object, Object, Object, Object, Boolean), ByVal paramNames As IList(Of String)) CheckParamCount(7, paramNames) _predicateDict.Add(New Tuple(Of Object, IList(Of String))(predicate, paramNames)) End Sub Public Sub AddRequire(ByVal predicate As Func(Of Object, Object, Object, Object, Object, Object, Object, Object, Boolean), ByVal paramNames As IList(Of String)) CheckParamCount(8, paramNames) _predicateDict.Add(New Tuple(Of Object, IList(Of String))(predicate, paramNames)) End Sub Sub CheckParamCount(ByVal count As Integer, ByVal paramNames As IList(Of String)) If paramNames.Count <> count Then Throw New Exception("Parameter count does not match.") End If End Sub Public Property IterationOver As Boolean Private _firstTime As Boolean = True Public ReadOnly Property Current As Dictionary(Of String, Object) Get If IterationOver Then Return Nothing Else Dim _nextResult = New Dictionary(Of String, Object) For Each item In _paramDict Dim iter = item.Item2 _nextResult.Add(item.Item1, iter.Current) Next Return _nextResult End If End Get End Property Function MoveNext() As Boolean If IterationOver Then Return False End If If _firstTime Then For Each item In _paramDict Dim iter = item.Item2 iter.MoveNext() Next _firstTime = False Return True Else Dim canMoveNext = False Dim iterIndex = _paramDict.Count - 1 canMoveNext = _paramDict(iterIndex).Item2.MoveNext If canMoveNext Then Return True End If Do While Not canMoveNext iterIndex = iterIndex - 1 If iterIndex = -1 Then Return False IterationOver = True End If canMoveNext = _paramDict(iterIndex).Item2.MoveNext If canMoveNext Then For i = iterIndex + 1 To _paramDict.Count - 1 Dim iter = _paramDict(i).Item2 iter.Reset() iter.MoveNext() Next Return True End If Loop End If End Function Function GetNextResult() As Dictionary(Of String, Object) While MoveNext() Dim result = Current If Satisfy(result) Then Return result End If End While Return Nothing End Function Function Satisfy(ByVal result As Dictionary(Of String, Object)) As Boolean For Each item In _predicateDict Dim pred = item.Item1 Select Case item.Item2.Count Case 1 Dim p1 = DirectCast(pred, Func(Of Object, Boolean)) Dim v1 = result(item.Item2(0)) If Not p1(v1) Then Return False End If Case 2 Dim p2 = DirectCast(pred, Func(Of Object, Object, Boolean)) Dim v1 = result(item.Item2(0)) Dim v2 = result(item.Item2(1)) If Not p2(v1, v2) Then Return False End If Case 3 Dim p3 = DirectCast(pred, Func(Of Object, Object, Object, Boolean)) Dim v1 = result(item.Item2(0)) Dim v2 = result(item.Item2(1)) Dim v3 = result(item.Item2(2)) If Not p3(v1, v2, v3) Then Return False End If Case 4 Dim p4 = DirectCast(pred, Func(Of Object, Object, Object, Object, Boolean)) Dim v1 = result(item.Item2(0)) Dim v2 = result(item.Item2(1)) Dim v3 = result(item.Item2(2)) Dim v4 = result(item.Item2(3)) If Not p4(v1, v2, v3, v4) Then Return False End If Case 5 Dim p5 = DirectCast(pred, Func(Of Object, Object, Object, Object, Object, Boolean)) Dim v1 = result(item.Item2(0)) Dim v2 = result(item.Item2(1)) Dim v3 = result(item.Item2(2)) Dim v4 = result(item.Item2(3)) Dim v5 = result(item.Item2(4)) If Not p5(v1, v2, v3, v4, v5) Then Return False End If Case 6 Dim p6 = DirectCast(pred, Func(Of Object, Object, Object, Object, Object, Object, Boolean)) Dim v1 = result(item.Item2(0)) Dim v2 = result(item.Item2(1)) Dim v3 = result(item.Item2(2)) Dim v4 = result(item.Item2(3)) Dim v5 = result(item.Item2(4)) Dim v6 = result(item.Item2(5)) If Not p6(v1, v2, v3, v4, v5, v6) Then Return False End If Case 7 Dim p7 = DirectCast(pred, Func(Of Object, Object, Object, Object, Object, Object, Object, Boolean)) Dim v1 = result(item.Item2(0)) Dim v2 = result(item.Item2(1)) Dim v3 = result(item.Item2(2)) Dim v4 = result(item.Item2(3)) Dim v5 = result(item.Item2(4)) Dim v6 = result(item.Item2(5)) Dim v7 = result(item.Item2(6)) If Not p7(v1, v2, v3, v4, v5, v6, v7) Then Return False End If Case 8 Dim p8 = DirectCast(pred, Func(Of Object, Object, Object, Object, Object, Object, Object, Object, Boolean)) Dim v1 = result(item.Item2(0)) Dim v2 = result(item.Item2(1)) Dim v3 = result(item.Item2(2)) Dim v4 = result(item.Item2(3)) Dim v5 = result(item.Item2(4)) Dim v6 = result(item.Item2(5)) Dim v7 = result(item.Item2(6)) Dim v8 = result(item.Item2(7)) If Not p8(v1, v2, v3, v4, v5, v6, v7, v8) Then Return False End If Case Else Throw New NotSupportedException End Select Next Return True End FunctionEnd Class    And now we can use the engine to solve the problem we mentioned above:   Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--Sub Test2() Dim engine = New NonDeterministicEngine() engine.AddParam("baker", {1, 2, 3, 4, 5}) engine.AddParam("cooper", {1, 2, 3, 4, 5}) engine.AddParam("fletcher", {1, 2, 3, 4, 5}) engine.AddParam("miller", {1, 2, 3, 4, 5}) engine.AddParam("smith", {1, 2, 3, 4, 5}) engine.AddRequire(Function(baker) As Boolean Return baker <> 5 End Function, {"baker"}) engine.AddRequire(Function(cooper) As Boolean Return cooper <> 1 End Function, {"cooper"}) engine.AddRequire(Function(fletcher) As Boolean Return fletcher <> 1 And fletcher <> 5 End Function, {"fletcher"}) engine.AddRequire(Function(miller, cooper) As Boolean 'Return miller = cooper + 1 Return miller > cooper End Function, {"miller", "cooper"}) engine.AddRequire(Function(smith, fletcher) As Boolean Return smith <> fletcher + 1 And smith <> fletcher - 1 End Function, {"smith", "fletcher"}) engine.AddRequire(Function(fletcher, cooper) As Boolean Return fletcher <> cooper + 1 And fletcher <> cooper - 1 End Function, {"fletcher", "cooper"}) engine.AddRequire(Function(a, b, c, d, e) As Boolean Return a <> b And a <> c And a <> d And a <> e And b <> c And b <> d And b <> e And c <> d And c <> e And d <> e End Function, {"baker", "cooper", "fletcher", "miller", "smith"}) Dim result = engine.GetNextResult() While Not result Is Nothing Console.WriteLine(String.Format("baker: {0}, cooper: {1}, fletcher: {2}, miller: {3}, smith: {4}", result("baker"), result("cooper"), result("fletcher"), result("miller"), result("smith"))) result = engine.GetNextResult() End While Console.WriteLine("Calculation ended.")End Sub   Also, this engine can solve the classic 8 queens puzzle and find out all 92 results for me.   Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--Sub Test3() ' The 8-Queens problem. Dim engine = New NonDeterministicEngine() ' Let's assume that a - h represents the queens in row 1 to 8, then we just need to find out the column number for each of them. engine.AddParam("a", {1, 2, 3, 4, 5, 6, 7, 8}) engine.AddParam("b", {1, 2, 3, 4, 5, 6, 7, 8}) engine.AddParam("c", {1, 2, 3, 4, 5, 6, 7, 8}) engine.AddParam("d", {1, 2, 3, 4, 5, 6, 7, 8}) engine.AddParam("e", {1, 2, 3, 4, 5, 6, 7, 8}) engine.AddParam("f", {1, 2, 3, 4, 5, 6, 7, 8}) engine.AddParam("g", {1, 2, 3, 4, 5, 6, 7, 8}) engine.AddParam("h", {1, 2, 3, 4, 5, 6, 7, 8}) Dim NotInTheSameDiagonalLine = Function(cols As IList) As Boolean For i = 0 To cols.Count - 2 For j = i + 1 To cols.Count - 1 If j - i = Math.Abs(cols(j) - cols(i)) Then Return False End If Next Next Return True End Function engine.AddRequire(Function(a, b, c, d, e, f, g, h) As Boolean Return a <> b AndAlso a <> c AndAlso a <> d AndAlso a <> e AndAlso a <> f AndAlso a <> g AndAlso a <> h AndAlso b <> c AndAlso b <> d AndAlso b <> e AndAlso b <> f AndAlso b <> g AndAlso b <> h AndAlso c <> d AndAlso c <> e AndAlso c <> f AndAlso c <> g AndAlso c <> h AndAlso d <> e AndAlso d <> f AndAlso d <> g AndAlso d <> h AndAlso e <> f AndAlso e <> g AndAlso e <> h AndAlso f <> g AndAlso f <> h AndAlso g <> h AndAlso NotInTheSameDiagonalLine({a, b, c, d, e, f, g, h}) End Function, {"a", "b", "c", "d", "e", "f", "g", "h"}) Dim result = engine.GetNextResult() While Not result Is Nothing Console.WriteLine("(1,{0}), (2,{1}), (3,{2}), (4,{3}), (5,{4}), (6,{5}), (7,{6}), (8,{7})", result("a"), result("b"), result("c"), result("d"), result("e"), result("f"), result("g"), result("h")) result = engine.GetNextResult() End While Console.WriteLine("Calculation ended.")End Sub (Chinese version of the post: http://www.cnblogs.com/RChen/archive/2010/05/17/1737587.html) Cheers,  

    Read the article

  • WPF Blurry Images - Bitmap Class

    - by Luke
    I am using the following sample at http://blogs.msdn.com/dwayneneed/archive/2007/10/05/blurry-bitmaps.aspx within VB.NET. The code is shown below. I am having a problem when my application loads the CPU is pegging 50-70%. I have determined that the problem is with the Bitmap class. The OnLayoutUpdated() method is calling the InvalidateVisual() continously. This is because some points are not returning as equal but rather, Point(0.0,-0.5) Can anyone see any bugs within this code or know a better implmentation for pixel snapping a Bitmap image so it is not blurry? p.s. The sample code was in C#, however I believe that it was converted correctly. Imports System Imports System.Collections.Generic Imports System.Windows Imports System.Windows.Media Imports System.Windows.Media.Imaging Class Bitmap Inherits FrameworkElement ' Use FrameworkElement instead of UIElement so Data Binding works as expected Private _sourceDownloaded As EventHandler Private _sourceFailed As EventHandler(Of ExceptionEventArgs) Private _pixelOffset As Windows.Point Public Sub New() _sourceDownloaded = New EventHandler(AddressOf OnSourceDownloaded) _sourceFailed = New EventHandler(Of ExceptionEventArgs)(AddressOf OnSourceFailed) AddHandler LayoutUpdated, AddressOf OnLayoutUpdated End Sub Public Shared ReadOnly SourceProperty As DependencyProperty = DependencyProperty.Register("Source", GetType(BitmapSource), GetType(Bitmap), New FrameworkPropertyMetadata(Nothing, FrameworkPropertyMetadataOptions.AffectsRender Or FrameworkPropertyMetadataOptions.AffectsMeasure, New PropertyChangedCallback(AddressOf Bitmap.OnSourceChanged))) Public Property Source() As BitmapSource Get Return DirectCast(GetValue(SourceProperty), BitmapSource) End Get Set(ByVal value As BitmapSource) SetValue(SourceProperty, value) End Set End Property Public Shared Function FindParentWindow(ByVal child As DependencyObject) As Window Dim parent As DependencyObject = VisualTreeHelper.GetParent(child) 'Check if this is the end of the tree If parent Is Nothing Then Return Nothing End If Dim parentWindow As Window = TryCast(parent, Window) If parentWindow IsNot Nothing Then Return parentWindow Else ' Use recursion until it reaches a Window Return FindParentWindow(parent) End If End Function Public Event BitmapFailed As EventHandler(Of ExceptionEventArgs) ' Return our measure size to be the size needed to display the bitmap pixels. ' ' Use MeasureOverride instead of MeasureCore so Data Binding works as expected. ' Protected Overloads Overrides Function MeasureCore(ByVal availableSize As Size) As Size Protected Overloads Overrides Function MeasureOverride(ByVal availableSize As Size) As Size Dim measureSize As New Size() Dim bitmapSource As BitmapSource = Source If bitmapSource IsNot Nothing Then Dim ps As PresentationSource = PresentationSource.FromVisual(Me) If Me.VisualParent IsNot Nothing Then Dim window As Window = window.GetWindow(Me.VisualParent) If window IsNot Nothing Then ps = PresentationSource.FromVisual(window.GetWindow(Me.VisualParent)) ElseIf FindParentWindow(Me) IsNot Nothing Then ps = PresentationSource.FromVisual(FindParentWindow(Me)) End If End If ' If ps IsNot Nothing Then Dim fromDevice As Matrix = ps.CompositionTarget.TransformFromDevice Dim pixelSize As New Vector(bitmapSource.PixelWidth, bitmapSource.PixelHeight) Dim measureSizeV As Vector = fromDevice.Transform(pixelSize) measureSize = New Size(measureSizeV.X, measureSizeV.Y) Else measureSize = New Size(bitmapSource.PixelWidth, bitmapSource.PixelHeight) End If End If Return measureSize End Function Protected Overloads Overrides Sub OnRender(ByVal dc As DrawingContext) Dim bitmapSource As BitmapSource = Me.Source If bitmapSource IsNot Nothing Then _pixelOffset = GetPixelOffset() ' Render the bitmap offset by the needed amount to align to pixels. dc.DrawImage(bitmapSource, New Rect(_pixelOffset, DesiredSize)) End If End Sub Private Shared Sub OnSourceChanged(ByVal d As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs) Dim bitmap As Bitmap = DirectCast(d, Bitmap) Dim oldValue As BitmapSource = DirectCast(e.OldValue, BitmapSource) Dim newValue As BitmapSource = DirectCast(e.NewValue, BitmapSource) If ((oldValue IsNot Nothing) AndAlso (bitmap._sourceDownloaded IsNot Nothing)) AndAlso (Not oldValue.IsFrozen AndAlso (TypeOf oldValue Is BitmapSource)) Then RemoveHandler DirectCast(oldValue, BitmapSource).DownloadCompleted, bitmap._sourceDownloaded RemoveHandler DirectCast(oldValue, BitmapSource).DownloadFailed, bitmap._sourceFailed ' ((BitmapSource)newValue).DecodeFailed -= bitmap._sourceFailed; // 3.5 End If If ((newValue IsNot Nothing) AndAlso (TypeOf newValue Is BitmapSource)) AndAlso Not newValue.IsFrozen Then AddHandler DirectCast(newValue, BitmapSource).DownloadCompleted, bitmap._sourceDownloaded AddHandler DirectCast(newValue, BitmapSource).DownloadFailed, bitmap._sourceFailed ' ((BitmapSource)newValue).DecodeFailed += bitmap._sourceFailed; // 3.5 End If End Sub Private Sub OnSourceDownloaded(ByVal sender As Object, ByVal e As EventArgs) InvalidateMeasure() InvalidateVisual() End Sub Private Sub OnSourceFailed(ByVal sender As Object, ByVal e As ExceptionEventArgs) Source = Nothing ' setting a local value seems scetchy... RaiseEvent BitmapFailed(Me, e) End Sub Private Sub OnLayoutUpdated(ByVal sender As Object, ByVal e As EventArgs) ' This event just means that layout happened somewhere. However, this is ' what we need since layout anywhere could affect our pixel positioning. Dim pixelOffset As Windows.Point = GetPixelOffset() If Not AreClose(pixelOffset, _pixelOffset) Then InvalidateVisual() End If End Sub ' Gets the matrix that will convert a Windows.Point from "above" the ' coordinate space of a visual into the the coordinate space ' "below" the visual. Private Function GetVisualTransform(ByVal v As Visual) As Matrix If v IsNot Nothing Then Dim m As Matrix = Matrix.Identity Dim transform As Transform = VisualTreeHelper.GetTransform(v) If transform IsNot Nothing Then Dim cm As Matrix = transform.Value m = Matrix.Multiply(m, cm) End If Dim offset As Vector = VisualTreeHelper.GetOffset(v) m.Translate(offset.X, offset.Y) Return m End If Return Matrix.Identity End Function Private Function TryApplyVisualTransform(ByVal Point As Windows.Point, ByVal v As Visual, ByVal inverse As Boolean, ByVal throwOnError As Boolean, ByRef success As Boolean) As Windows.Point success = True If v IsNot Nothing Then Dim visualTransform As Matrix = GetVisualTransform(v) If inverse Then If Not throwOnError AndAlso Not visualTransform.HasInverse Then success = False Return New Windows.Point(0, 0) End If visualTransform.Invert() End If Point = visualTransform.Transform(Point) End If Return Point End Function Private Function ApplyVisualTransform(ByVal Point As Windows.Point, ByVal v As Visual, ByVal inverse As Boolean) As Windows.Point Dim success As Boolean = True Return TryApplyVisualTransform(Point, v, inverse, True, success) End Function Private Function GetPixelOffset() As Windows.Point Dim pixelOffset As New Windows.Point() Dim ps As PresentationSource = PresentationSource.FromVisual(Me) If ps IsNot Nothing Then Dim rootVisual As Visual = ps.RootVisual ' Transform (0,0) from this element up to pixels. pixelOffset = Me.TransformToAncestor(rootVisual).Transform(pixelOffset) pixelOffset = ApplyVisualTransform(pixelOffset, rootVisual, False) pixelOffset = ps.CompositionTarget.TransformToDevice.Transform(pixelOffset) ' Round the origin to the nearest whole pixel. pixelOffset.X = Math.Round(pixelOffset.X) pixelOffset.Y = Math.Round(pixelOffset.Y) ' Transform the whole-pixel back to this element. pixelOffset = ps.CompositionTarget.TransformFromDevice.Transform(pixelOffset) pixelOffset = ApplyVisualTransform(pixelOffset, rootVisual, True) pixelOffset = rootVisual.TransformToDescendant(Me).Transform(pixelOffset) End If Return pixelOffset End Function Private Function AreClose(ByVal Point1 As Windows.Point, ByVal Point2 As Windows.Point) As Boolean Return AreClose(Point1.X, Point2.X) AndAlso AreClose(Point1.Y, Point2.Y) End Function Private Function AreClose(ByVal value1 As Double, ByVal value2 As Double) As Boolean If value1 = value2 Then Return True End If Dim delta As Double = value1 - value2 Return ((delta < 0.00000153) AndAlso (delta > -0.00000153)) End Function End Class

    Read the article

  • Very interesting problem in Compact Framework

    - by Alexander
    Hi, i have a performance problem while inserting data to sqlce.I'm reading string and making inserts to My tables.In LU_MAM table,i insert 1000 records withing 8 seconds.After Mam tables i make some inserts but my largest table is CR_MUS.When i want to insert record into CR_MUS,it takes too much time.CR_MUS has 2000 records and insert takes 35 seconds.What can be reason?I use same logic in my insert functions.Do u have any idea?I use VS 2008 sp1. Dim reader As StringReader reader = New StringReader(data) cn = New SqlCeConnection(General.ConnString) cn.Open() If myTransfer.ClearTables(cn, cmd) = True Then progress = 0 '------------------------------------------ cmd = New SqlServerCe.SqlCeCommand Dim rs As SqlCeResultSet cmd.Connection = cn cmd.CommandType = CommandType.TableDirect Dim rec As SqlCeUpdatableRecord ' name of table While reader.Peek > -1 If strerr_col = "" Then satir = reader.ReadLine() ayrac = Split(satir, "|") If ayrac(0).ToString() = "LC" Then prgsbar.Maximum = Convert.ToInt32(ayrac(1)) ElseIf ayrac(0).ToString = "PPAR" Then . If ayrac(2).ToString <> General.PMVer Then ShowWaitCursor(False) txtDurum.Text = "Wrong Version" Exit Sub End If If p_POCKET_PARAMETERS = True Then cmd.CommandText = "POCKET_PARAMETERS" txtDurum.Text = "POCKET_PARAMETERS" rs = cmd.ExecuteResultSet(ResultSetOptions.Updatable) rec = rs.CreateRecord() p_POCKET_PARAMETERS = False End If strerr_col = myVERI_AL.POCKET_PARAMETERS_I(ayrac, cmd, rs, rec) prgsbar.Value += 1 ElseIf ayrac(0).ToString() = "MAM" Then If p_LU_MAM = True Then txtDurum.Text = "LU_MAM " cmd.CommandText = "LU_MAM" rs = cmd.ExecuteResultSet(ResultSetOptions.Updatable) rec = rs.CreateRecord() p_LU_MAM = False End If strerr_col = myVERI_AL.LU_MAM_I(ayrac, cmd, rs, rec) prgsbar.Value += 1 ElseIf ayrac(0).ToString = "KMUS" Then If p_CR_MUS = True Then cmd.CommandText = "CR_MUS" txtDurum.Text = "CR_MUS" rs = cmd.ExecuteResultSet(ResultSetOptions.Updatable) rec = rs.CreateRecord() p_TR_KAMPANYA_MALZEME = False End If strerr_col = myVERI_AL.CR_MUS_I(ayrac, cmd, rs, rec) prgsbar.Value += 1 end while Public Function CR_KAMPANYA_MUSTERI_I(ByVal f_Line() As String, ByRef myComm As SqlCeCommand, ByRef rs As SqlCeResultSet, ByRef rec As SqlCeUpdatableRecord) As String Try rec.SetValue(0, If(f_Line(1) = String.Empty, DirectCast(DBNull.Value, Object), f_Line(1))) rec.SetValue(1, If(f_Line(2) = String.Empty, DirectCast(DBNull.Value, Object), f_Line(2))) rec.SetValue(2, If(f_Line(3) = String.Empty, DirectCast(DBNull.Value, Object), f_Line(3))) rec.SetValue(3, If(f_Line(5) = String.Empty, DirectCast(DBNull.Value, Object), f_Line(5))) rec.SetValue(4, If(f_Line(6) = String.Empty, DirectCast(DBNull.Value, Object), f_Line(6))) rs.Insert(rec) Catch ex As Exception strerr_col = ex.Message End Try Return strerr_col End Function

    Read the article

  • Not getting redirection to custom error page using custom errors - ASP.Net

    - by weevie
    Here's my Application_OnError event sink in global.asax.vb: Sub Application_OnError(ByVal sender As Object, ByVal e As EventArgs) Dim innerMostException As Exception = getInnerMostException(Me.Context.Error) If TypeOf innerMostException Is AccessDeniedException Then Security.LogAccessDeniedOccurrence(DirectCast(innerMostException, AccessDeniedException)) Dim fourOhThree As Integer = DirectCast(HttpStatusCode.Forbidden, Integer) Throw New HttpException(fourOhThree, innerMostException.Message, innerMostException) End If End Sub You'll see that if we've got an innermost Exception of type AccessDeniedException we throw a new HTTPExcpetion with a status code of 403 AKA 'forbidden' Here's the relevant web.config entry: <customErrors defaultRedirect="~/Application/ServerError.aspx" mode="On"> <error statusCode="403" redirect="~/Secure/AccessDenied.aspx" /> </customErrors> So what we're expecting is a redirect to the AccessDenied.aspx page. What we get is a redirect to the ServerError.aspx page. We've also tried this: Sub Application_OnError(ByVal sender As Object, ByVal e As EventArgs) Dim innerMostException As Exception = getInnerMostException(Me.Context.Error) If TypeOf innerMostException Is AccessDeniedException Then Security.LogAccessDeniedOccurrence(DirectCast(innerMostException, AccessDeniedException)) Context.Response.StatusCode = DirectCast(HttpStatusCode.Forbidden, Integer) End If End Sub Which unsuprisingly doesn't work either. Any ideas what we're doing wrong?

    Read the article

  • VB.Net Dynamically Load DLL

    - by hermiod
    I am trying to write some code that will allow me to dynamically load DLLs into my application, depending on an application setting. The idea is that the database to be accessed is set in the application settings and then this loads the appropriate DLL and assigns it to an instance of an interface for my application to access. This is my code at the moment: Dim SQLDataSource As ICRDataLayer Dim ass As Assembly = Assembly. _ LoadFrom("M:\MyProgs\WebService\DynamicAssemblyLoading\SQLServer\bin\Debug\SQLServer.dll") Dim obj As Object = ass.CreateInstance(GetType(ICRDataLayer).ToString, True) SQLDataSource = DirectCast(obj, ICRDataLayer) MsgBox(SQLDataSource.ModuleName & vbNewLine & SQLDataSource.ModuleDescription) I have my interface (ICRDataLayer) and the SQLServer.dll contains an implementation of this interface. I just want to load the assembly and assign it to the SQLDataSource object. The above code just doesn't work. There are no exceptions thrown, even the Msgbox doesn't appear. I would've expected at least the messagebox appearing with nothing in it, but even this doesn't happen! Is there a way to determine if the loaded assembly implements a specific interface. I tried the below but this also doesn't seem to do anything! For Each loadedType As Type In ass.GetTypes If GetType(ICRDataLayer).IsAssignableFrom(loadedType) Then Dim obj1 As Object = ass.CreateInstance(GetType(ICRDataLayer).ToString, True) SQLDataSource = DirectCast(obj1, ICRDataLayer) End If Next EDIT: New code from Vlad's examples: Module CRDataLayerFactory Sub New() End Sub ' class name is a contract, ' should be the same for all plugins Private Function Create() As ICRDataLayer Return New SQLServer() End Function End Module Above is Module in each DLL, converted from Vlad's C# example. Below is my code to bring in the DLL: Dim SQLDataSource As ICRDataLayer Dim ass As Assembly = Assembly. _ LoadFrom("M:\MyProgs\WebService\DynamicAssemblyLoading\SQLServer\bin\Debug\SQLServer.dll") Dim factory As Object = ass.CreateInstance("CRDataLayerFactory", True) Dim t As Type = factory.GetType Dim method As MethodInfo = t.GetMethod("Create") Dim obj As Object = method.Invoke(factory, Nothing) SQLDataSource = DirectCast(obj, ICRDataLayer) EDIT: Implementation based on Paul Kohler's code Dim file As String For Each file In Directory.GetFiles(baseDir, searchPattern, SearchOption.TopDirectoryOnly) Dim assemblyType As System.Type For Each assemblyType In Assembly.LoadFrom(file).GetTypes Dim s As System.Type() = assemblyType.GetInterfaces For Each ty As System.Type In s If ty.Name.Contains("ICRDataLayer") Then MsgBox(ty.Name) plugin = DirectCast(Activator.CreateInstance(assemblyType), ICRDataLayer) MessageBox.Show(plugin.ModuleName) End If Next I get the following error with this code: Unable to cast object of type 'SQLServer.CRDataSource.SQLServer' to type 'DynamicAssemblyLoading.ICRDataLayer'. The actual DLL is in a different project called SQLServer in the same solution as my implementation code. CRDataSource is a namespace and SQLServer is the actual class name of the DLL. The SQLServer class implements ICRDataLayer, so I don't understand why it wouldn't be able to cast it. Is the naming significant here, I wouldn't have thought it would be.

    Read the article

  • Using returned XML from an authorised HTTP request in vb.NET

    - by Nathan
    Hi, How can I use the returned XML from the reader in a xmltextreader? ' Create the web request request = DirectCast(WebRequest.Create("https://mobilevikings.com/api/1.0/rest/mobilevikings/sim_balance.xml"), HttpWebRequest) ' Add authentication to request request.Credentials = New NetworkCredential("username", "password") ' Get response response = DirectCast(request.GetResponse(), HttpWebResponse) ' Get the response stream into a reader reader = New StreamReader(response.GetResponseStream()) Thanks in advance, Nathan.

    Read the article

  • .Net Dynamically Load DLL

    - by hermiod
    I am trying to write some code that will allow me to dynamically load DLLs into my application, depending on an application setting. The idea is that the database to be accessed is set in the application settings and then this loads the appropriate DLL and assigns it to an instance of an interface for my application to access. This is my code at the moment: Dim SQLDataSource As ICRDataLayer Dim ass As Assembly = Assembly. _ LoadFrom("M:\MyProgs\WebService\DynamicAssemblyLoading\SQLServer\bin\Debug\SQLServer.dll") Dim obj As Object = ass.CreateInstance(GetType(ICRDataLayer).ToString, True) SQLDataSource = DirectCast(obj, ICRDataLayer) MsgBox(SQLDataSource.ModuleName & vbNewLine & SQLDataSource.ModuleDescription) I have my interface (ICRDataLayer) and the SQLServer.dll contains an implementation of this interface. I just want to load the assembly and assign it to the SQLDataSource object. The above code just doesn't work. There are no exceptions thrown, even the Msgbox doesn't appear. I would've expected at least the messagebox appearing with nothing in it, but even this doesn't happen! Is there a way to determine if the loaded assembly implements a specific interface. I tried the below but this also doesn't seem to do anything! For Each loadedType As Type In ass.GetTypes If GetType(ICRDataLayer).IsAssignableFrom(loadedType) Then Dim obj1 As Object = ass.CreateInstance(GetType(ICRDataLayer).ToString, True) SQLDataSource = DirectCast(obj1, ICRDataLayer) End If Next EDIT: New code from Vlad's examples: Module CRDataLayerFactory Sub New() End Sub ' class name is a contract, ' should be the same for all plugins Private Function Create() As ICRDataLayer Return New SQLServer() End Function End Module Above is Module in each DLL, converted from Vlad's C# example. Below is my code to bring in the DLL: Dim SQLDataSource As ICRDataLayer Dim ass As Assembly = Assembly. _ LoadFrom("M:\MyProgs\WebService\DynamicAssemblyLoading\SQLServer\bin\Debug\SQLServer.dll") Dim factory As Object = ass.CreateInstance("CRDataLayerFactory", True) Dim t As Type = factory.GetType Dim method As MethodInfo = t.GetMethod("Create") Dim obj As Object = method.Invoke(factory, Nothing) SQLDataSource = DirectCast(obj, ICRDataLayer) EDIT: Implementation based on Paul Kohler's code Dim file As String For Each file In Directory.GetFiles(baseDir, searchPattern, SearchOption.TopDirectoryOnly) Dim assemblyType As System.Type For Each assemblyType In Assembly.LoadFrom(file).GetTypes Dim s As System.Type() = assemblyType.GetInterfaces For Each ty As System.Type In s If ty.Name.Contains("ICRDataLayer") Then MsgBox(ty.Name) plugin = DirectCast(Activator.CreateInstance(assemblyType), ICRDataLayer) MessageBox.Show(plugin.ModuleName) End If Next I get the following error with this code: Unable to cast object of type 'SQLServer.CRDataSource.SQLServer' to type 'DynamicAssemblyLoading.ICRDataLayer'. The actual DLL is in a different project called SQLServer in the same solution as my implementation code. CRDataSource is a namespace and SQLServer is the actual class name of the DLL. The SQLServer class implements ICRDataLayer, so I don't understand why it wouldn't be able to cast it. Is the naming significant here, I wouldn't have thought it would be.

    Read the article

  • Dynamically created LinkButton not firing any events

    - by Brent
    I'm customising the Group Headers on a Telerik RadGrid by injecting a LinkButton into it during the ItemDataBound event. The button renders perfectly, but I can't get it to hit any event handlers. Here is the code for the button creation: Private Sub rgWorkRequestItemCosts_ItemDataBound(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridItemEventArgs) Handles rgWorkRequestItemCosts.ItemDataBound If TypeOf e.Item Is GridGroupHeaderItem Then Dim oItem As GridGroupHeaderItem = DirectCast(e.Item, GridGroupHeaderItem) Dim lnkAdd As New LinkButton() lnkAdd.ID = "lnkAdd" lnkAdd.CommandName = "CustomAddWorkRequestItemCost" lnkAdd.CommandArgument = DirectCast(oItem.DataItem, DataRowView).Row("nWorkRequestItemID").ToString() lnkAdd.Text = String.Format("<img style=""border:0px"" alt="""" width=""12"" src=""{0}"" /> Add new cost", ResolveUrl(String.Format("~/App_Themes/{0}/Grid/AddRecord.gif", Page.Theme))) lnkAdd.Style("color") = "#000000" lnkAdd.Style("text-decoration") = "none" AddHandler lnkAdd.Click, AddressOf lnkAdd_Click Dim tcPlaceholder As GridTableCell = DirectCast(oItem.Controls(1), GridTableCell) Dim litText As New LiteralControl(String.Format("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{0}", tcPlaceholder.Text)) tcPlaceholder.Text = String.Empty tcPlaceholder.Controls.Add(lnkAdd) tcPlaceholder.Controls.Add(litText) End If End Sub This code explicitly adds a handler for the LinkButton, but that handler is never hit. I've also tried events on the RadGrid (ItemCommand, ItemEvent) but none seem to get hit. Has anyone got any suggestions of other events to try, or ways to make this work? Thanks!

    Read the article

  • How do I DYNAMICALLY cast in C# and return for a property

    - by ken-forslund
    I've already read threads on the topic, but can't find a solution that fits. I'm working on a drop-down list that takes an enum and uses that to populate itself. i found a VB.NET one. During the porting process, I discovered that it uses DirectCast() to set the type as it returns the SelectedValue. See the original VB here: http://jeffhandley.com/archive/2008/01/27/enum-list-dropdown-control.aspx the gist is, the control has Type _enumType; //gets set when the datasource is set and is the type of the specific enum The SelectedValue property kind of looks like (remember, it doesn't work): public Enum SelectedValue //Shadows Property { get { // Get the value from the request to allow for disabled viewstate string RequestValue = this.Page.Request.Params[this.UniqueID]; return Enum.Parse(_enumType, RequestValue, true) as _enumType; } set { base.SelectedValue = value.ToString(); } } Now this touches on a core point that I think was missed in the other discussions. In darn near every example, folks argued that DirectCast wasn't needed, because in every example, they statically defined the type. That's not the case here. As the programmer of the control, I don't know the type. Therefore, I can't cast it. Additionally, the following examples of lines won't compile because c# casting doesn't accept a variable. Whereas VB's CType and DirectCast can accept Type T as a function parameter: return Enum.Parse(_enumType, RequestValue, true); or return Enum.Parse(_enumType, RequestValue, true) as _enumType; or return (_enumType)Enum.Parse(_enumType, RequestValue, true) ; or return Convert.ChangeType(Enum.Parse(_enumType, RequestValue, true), _enumType); or return CastTo<_enumType>(Enum.Parse(_enumType, RequestValue, true)); So, any ideas on a solution? What's the .NET 3.5 best way to resolve this?

    Read the article

  • ListBoxItem.Parent returns nothing, unable to get it thru VisualTreeHelper.GetParent either

    - by Shimmy
    How do I extract the parent container of a ListBoxItem? In the following example I can go till the ListBoxItem, higher than that I get Nothing: <ListBox Name="lbAddress"> <ListBox.ItemTemplate> <DataTemplate> <Button Click="Button_Click"/> </DataTemplate> </ListBox.ItemTemplate> </ListBox> Private Sub Button_Click(sender As Button, e As RoutedEventArgs) Dim lbAddress = GetAncestor(Of ListBox) 'Result: Nothing End Sub Public Shared Function GetAncestor(Of T)(reference As DependencyObject) As T Dim parent = GetParent(reference) While parent IsNot Nothing AndAlso Not parent.GetType.Equals(GetType(T)) parent = GetAncestor(Of T)(parent) End While If parent IsNot Nothing Then _ Return If(parent.GetType Is GetType(T), parent, Nothing) Return Nothing End Sub Public Function GetParent(reference As DependencyObject) As DependencyObject Dim parent As DependencyObject = Nothing If TypeOf reference Is FrameworkElement Then parent = DirectCast(reference, FrameworkElement).Parent ElseIf TypeOf reference Is FrameworkContentElement Then parent = DirectCast(reference, FrameworkContentElement).Parent End If Return If(parent, VisualTreeHelper.GetParent(reference)) End Function Update This is what happens (note that the 'parent' variable remains null):

    Read the article

  • Find ListBox from its child?

    - by Shimmy
    How do I extract the parent container of a ListBoxItem? In the following example I can go till the ListBoxItem, higher than that I get Nothing: <ListBox Name="lbAddress"> <ListBox.ItemTemplate> <DataTemplate> <Button Click="Button_Click"/> </DataTemplate> </ListBox.ItemTemplate> </ListBox> Private Sub Button_Click(sender As Button, e As RoutedEventArgs) Dim lbAddress = GetAncestor(Of ListBox) 'Result: Nothing End Sub Public Shared Function GetAncestor(Of T)(reference As DependencyObject) As T Dim parent = GetParent(reference) While parent IsNot Nothing AndAlso Not parent.GetType.Equals(GetType(T)) parent = GetVisualAncestor(Of T)(parent) End While If parent IsNot Nothing Then _ Return If(parent.GetType Is GetType(T), parent, Nothing) Return Nothing End Sub Public Function GetParent(reference As DependencyObject) As DependencyObject Dim parent As DependencyObject = Nothing If TypeOf reference Is FrameworkElement Then parent = DirectCast(reference, FrameworkElement).Parent ElseIf TypeOf reference Is FrameworkContentElement Then parent = DirectCast(reference, FrameworkContentElement).Parent End If Return If(parent, VisualTreeHelper.GetParent(reference)) End Function

    Read the article

  • VB.NET, make a function with return type generic ?

    - by Quandary
    Currently I have written a function to deserialize XML as seen below. How do I change it so I don't have to replace the type every time I want to serialize another object type ? The current object type is cToolConfig. How do I make this function generic ? Public Shared Function DeserializeFromXML(ByRef strFileNameAndPath As String) As XMLhandler.XMLserialization.cToolConfig Dim deserializer As New System.Xml.Serialization.XmlSerializer(GetType(cToolConfig)) Dim srEncodingReader As IO.StreamReader = New IO.StreamReader(strFileNameAndPath, System.Text.Encoding.UTF8) Dim ThisFacility As cToolConfig ThisFacility = DirectCast(deserializer.Deserialize(srEncodingReader), cToolConfig) srEncodingReader.Close() srEncodingReader.Dispose() Return ThisFacility End Function Public Shared Function DeserializeFromXML1(ByRef strFileNameAndPath As String) As System.Collections.Generic.List(Of XMLhandler.XMLserialization.cToolConfig) Dim deserializer As New System.Xml.Serialization.XmlSerializer(GetType(System.Collections.Generic.List(Of cToolConfig))) Dim srEncodingReader As IO.StreamReader = New IO.StreamReader(strFileNameAndPath, System.Text.Encoding.UTF8) Dim FacilityList As System.Collections.Generic.List(Of cToolConfig) FacilityList = DirectCast(deserializer.Deserialize(srEncodingReader), System.Collections.Generic.List(Of cToolConfig)) srEncodingReader.Close() srEncodingReader.Dispose() Return FacilityList End Function

    Read the article

  • Entity Data Model & DataGridView - Creating new objects

    - by AcousticBoom
    I'm pretty new to the EDM, so bear with me. I have a windows form that has a DataGridView on it that's bound from the EDM I created. I figured out how to update my changes fine, but it's when the user creates a new row that I'm having a problem. I tried numerous ways and many google searches, but came up with nothing so far. Here's how the data is loaded: Dim boilerID As Integer = DirectCast(ddlBoiler.SelectedValue, Integer) Dim countryID As Integer = DirectCast(ddlCountry.SelectedValue, Integer) Dim ratings = From r In _Context.Rating _ Where r.Boiler.Boiler_ID = boilerID _ And r.Country.Country_ID = countryID _ Order By r.Sequence _ Select r RatingBindingSource.DataSource = ratings.ToList() Also, all I'm doing to save the information right now is the following: Private Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click _Context.SaveChanges() End Sub I want the user to be able to use the grid's "new row" feature to add new items to the database instead of having to click a button and open a new dialog. How would this be accomplished? I can include some of the methods i tried for adding new items if anyone needs to see. Thanks!

    Read the article

  • VB.NET handling data between different forms

    - by niuchu
    Hi, I'm writing a simple application - address book. User enters new addresses and they are added as an entry to a list visible on the main form (frmStart). I use one form to add and edit (AddContForm). Add button on the frmStart works fine, however I experience some problems with the edit button as when I press it and enter new data they are added as new entry however the previous entry is still there. Logic is handled by Contact.vb class. Please let me know how to fix this problem. Here is the code: Contact.vb Public Class Contact Public Contact As String Public Title As String Public Fname As String Public Surname As String Public Address As String Private myCont As String Public Property Cont() Get Return myCont End Get Set(ByVal value) myCont = Value End Set End Property Public Overrides Function ToString() As String Return Me.Cont End Function Public Sub Display() Dim C As New Contact C.Cont = frmAddCont.txtTitle.Text C.Fname = frmAddCont.txtFName.Text C.Surname = frmAddCont.txtSName.Text C.Address = frmAddCont.txtAddress.Text frmStart.lstContact.Items.Add(C) End Sub End Class Here is frmStart.vb Public Class frmStart Public Button As String Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click Button = "" Button = "Add" frmAddCont.ShowDialog() End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDel.Click Button = "" Button = "Del" Dim DelCont As Contact DelCont = Me.lstContact.SelectedItem() lstContact.Items.Remove(DelCont) End Sub Private Sub lstContact_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstContact.SelectedIndexChanged End Sub Private Sub btnEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEdit.Click Button = "" Button = "Edit" Dim C As Contact If lstContact.SelectedItem IsNot Nothing Then C = DirectCast(lstContact.SelectedItem, Contact) frmAddCont.ShowDialog() End If End Sub End Class Here is AddContFrm.vb Public Class frmAddCont Public Class ControlObject Dim Title As String Dim FName As String Dim SName As String Dim Address As String Dim TelephoneNumber As Integer Dim emailAddress As String Dim Website As String Dim Photograph As String End Class Private Sub btnConfirmAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConfirmAdd.Click Dim B As String B = frmStart.Button Dim C As New Contact C.Display() Me.Hide() If B = "Edit" Then C = DirectCast(frmStart.lstContact.SelectedItem, Contact) frmStart.lstContact.SelectedItems.Remove(C) End If End Sub Private Sub frmAddCont_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load End Sub End Class

    Read the article

  • Getting the highest owner of a ToolStripDropDownItem

    - by andyperfect
    I'm currently working on a project in which at one point, the user may right click a button which brings up a contextMenuStrip. I am already able to find the owner accurately from that strip, and manipulate the button clicked as follows: Dim myItem As ToolStripMenuItem = CType(sender, ToolStripMenuItem) Dim cms As ContextMenuStrip = CType(myItem.Owner, ContextMenuStrip) Dim buttonPressed As DataButton = DirectCast(cms.SourceControl, DataButton) But now for the tricky part. Within this contextmenuStrip, I have a DropDown menu with multiple items in there. I would assume you would be able to work your way up the ladder doing casts like above in the manner of ToolStripDrowpDownItem > ToolStripDropDownMenu > ToolStripMenuItem > ContextMenuStrip Unfortunately, when I try to get the sourcecontrol from this menuStrip, it return Nothing. Any ideas on how I can get the button that was pressed from this toolStripMenuItem? My current code is as follows (in which the sourceControl is Nothing) Dim myItem As ToolStripDropDownItem = CType(sender, ToolStripDropDownItem) Dim dropDown As ToolStripDropDownMenu = CType(myItem.Owner, ToolStripDropDownMenu) Dim menuItem As ToolStripMenuItem = CType(dropDown.OwnerItem, ToolStripMenuItem) Dim cms As ContextMenuStrip = CType(menuItem.Owner, ContextMenuStrip) Dim buttonPressed As DataButton = DirectCast(cms.SourceControl, DataButton) Any ideas on how to go about doing what I did in that first method, but just working my way up from further down the ladder?

    Read the article

  • Display post data !

    - by Comii
    I am trying to post data from vb.net application to web service asmx that is located on server! For posting data from vb.net application I am using this code: Public Function Post(ByVal url As String, ByVal data As String) As String Dim vystup As String = Nothing Try 'Our postvars Dim buffer As Byte() = Encoding.ASCII.GetBytes(data) 'Initialisation, we use localhost, change if appliable Dim WebReq As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest) 'Our method is post, otherwise the buffer (postvars) would be useless WebReq.Method = "POST" 'We use form contentType, for the postvars. WebReq.ContentType = "application/x-www-form-urlencoded" 'The length of the buffer (postvars) is used as contentlength. WebReq.ContentLength = buffer.Length 'We open a stream for writing the postvars Dim PostData As Stream = WebReq.GetRequestStream() 'Now we write, and afterwards, we close. Closing is always important! PostData.Write(buffer, 0, buffer.Length) PostData.Close() 'Get the response handle, we have no true response yet! Dim WebResp As HttpWebResponse = DirectCast(WebReq.GetResponse(), HttpWebResponse) 'Let's show some information about the response Console.WriteLine(WebResp.StatusCode) Console.WriteLine(WebResp.Server) 'Now, we read the response (the string), and output it. Dim Answer As Stream = WebResp.GetResponseStream() Dim _Answer As New StreamReader(Answer) 'Congratulations, you just requested your first POST page, you 'can now start logging into most login forms, with your application 'Or other examples. vystup = _Answer.ReadToEnd() Catch ex As Exception MessageBox.Show(ex.Message) End Try Return vystup.Trim() & vbLf End Function Now how i can retrieve this data in asmx service?

    Read the article

  • EPPlus - .xlsx is locked for editing by 'another user'

    - by AdamTheITMan
    I have searched through every possible answer on SO for a solution, but nothing has worked. I am basically creating an excel file from a database and sending the results to the response stream using EPPlus(OpenXML). The following code gives me an error when trying to open my generated excel sheet "[report].xlsx is locked for editing by 'another user'." It will open fine the first time, but the second time it's locked. Dim columnData As New List(Of Integer) Dim rowHeaders As New List(Of String) Dim letter As String = "B" Dim x As Integer = 0 Dim trendBy = context.Session("TRENDBY").ToString() Dim dateHeaders As New List(Of String) dateHeaders = DirectCast(context.Session("DATEHEADERS"), List(Of String)) Dim DS As New DataSet DS = DirectCast(context.Session("DS"), DataSet) Using excelPackage As New OfficeOpenXml.ExcelPackage Dim excelWorksheet = excelPackage.Workbook.Worksheets.Add("Report") 'Add title to the top With excelWorksheet.Cells("B1") .Value = "Account Totals by " + If(trendBy = "Months", "Month", "Week") .Style.Font.Bold = True End With 'add date headers x = 2 'start with letter B (aka 2) For Each Header As String In dateHeaders With excelWorksheet.Cells(letter + "2") .Value = Header .Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Right .AutoFitColumns() End With x = x + 1 letter = Helper.GetColumnIndexToColumnLetter(x) Next 'Adds the descriptive row headings down the left side of excel sheet x = 0 For Each DC As DataColumn In DS.Tables(0).Columns If (x < DS.Tables(0).Columns.Count) Then rowHeaders.Add(DC.ColumnName) End If Next Dim range = excelWorksheet.Cells("A3:A30") range.LoadFromCollection(rowHeaders) 'Add the meat and potatoes of report x = 2 For Each dTable As DataTable In DS.Tables columnData.Clear() For Each DR As DataRow In dTable.Rows For Each item As Object In DR.ItemArray columnData.Add(item) Next Next letter = Helper.GetColumnIndexToColumnLetter(x) excelWorksheet.Cells(letter + "3").LoadFromCollection(columnData) With excelWorksheet.Cells(letter + "3") .Formula = "=SUM(" + letter + "4:" + letter + "6)" .Style.Font.Bold = True .Style.Font.Size = 12 End With With excelWorksheet.Cells(letter + "7") .Formula = "=SUM(" + letter + "8:" + letter + "11)" .Style.Font.Bold = True .Style.Font.Size = 12 End With With excelWorksheet.Cells(letter + "12") .Style.Font.Bold = True .Style.Font.Size = 12 End With With excelWorksheet.Cells(letter + "13") .Formula = "=SUM(" + letter + "14:" + letter + "20)" .Style.Font.Bold = True .Style.Font.Size = 12 End With With excelWorksheet.Cells(letter + "21") .Formula = "=SUM(" + letter + "22:" + letter + "23)" .Style.Font.Bold = True .Style.Font.Size = 12 End With With excelWorksheet.Cells(letter + "24") .Formula = "=SUM(" + letter + "25:" + letter + "26)" .Style.Font.Bold = True .Style.Font.Size = 12 End With With excelWorksheet.Cells(letter + "27") .Formula = "=SUM(" + letter + "28:" + letter + "29)" .Style.Font.Bold = True .Style.Font.Size = 12 End With With excelWorksheet.Cells(letter + "30") .Formula = "=SUM(" + letter + "3," + letter + "7," + letter + "12," + letter + "13," + letter + "21," + letter + "24," + letter + "27)" .Style.Font.Bold = True .Style.Font.Size = 12 End With x = x + 1 Next range.AutoFitColumns() 'send it to response Using stream As New MemoryStream(excelPackage.GetAsByteArray()) context.Response.Clear() context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" context.Response.AddHeader("content-disposition", "attachment; filename=filetest.xlsx") context.Response.OutputStream.Write(stream.ToArray(), 0, stream.ToArray().Length) context.Response.Flush() context.Response.Close() End Using End Using

    Read the article

1 2 3  | Next Page >