Search Results

Search found 4472 results on 179 pages for 'vb'.

Page 70/179 | < Previous Page | 66 67 68 69 70 71 72 73 74 75 76 77  | Next Page >

  • "Find all tiles connected to this one" project

    - by Omega
    Remember MS Paint? The bucket tool? If you used it and clicked on a pixel, all pixels connected to this pixel that are the same are affected. The theory is, I suppose, to check if there is any pixel adjacent to the selected one. If such pixel is the same type as the selected one, check for more adjacent pixels in this one, and so on. I want to implement something similar in VB.NET. Basically I have a 2D array map which represents the map. Let's assume there are only two types of tile: 0 and 1. Now, I got pretty much everything ready: I got my 2d map and I can tell which tile is clicked and tell what array indexes are the ones that represent such tile. Now for the "painting" process. Whenever I think about it, I can't figure a convenient way to execute such iteration. Can someone help me choosing a correct design/way/tip to achieve this?

    Read the article

  • datagridviewcomboboxcolumn with datasource issue?

    - by Sarrrva
    i have some propblem in datagridviewcombobocolumn with custom datasource property in vb.net. when i add datasource it does not populate in datagridview combobox column it giving nothing.. any one please help me out from this problem... code comboboxcell: Public Overrides Sub InitializeEditingControl(ByVal rowIndex As Integer, ByVal initialFormattedValue As Object, ByVal dataGridViewCellStyle As DataGridViewCellStyle) ' Set the value of the editing control to the current cell value. MyBase.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle) Dim ctl As ComboEditingControl = CType(DataGridView.EditingControl, ComboEditingControl) ctl.DropDownStyle = ComboBoxStyle.DropDown ctl.AutoCompleteSource = AutoCompleteSource.ListItems ctl.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest If (Me.DataGridView.Rows(rowIndex).Cells(0).Value <> Nothing) Then Dim GetValueFromRowToUseForBuildingCombo As String = Me.DataGridView.Rows(rowIndex).Cells(0).Value.ToString() ctl.Items.Clear() Dim dt As New DataTable() Try dt = TryCast(DirectCast(Me.DataGridView.Columns(ColumnIndex), ComboColumn).DataSource, DataTable) Catch ex As Exception MsgBox("error") End Try If (dt Is Nothing) Then ctl.Items.Add("") Else Dim thing As DataRow For Each thing In dt.Rows ctl.Items.Add(thing(0).ToString) Next End If If Me.Value Is Nothing Then ctl.SelectedIndex = -1 Else ctl.SelectedItem = Me.Value End If ctl.EditingControlDataGridView = Me.DataGridView End If End Sub from code: Dim widgets As New WidgetDataHandler Dim obj = widgets.GetAllWigetTypes() Dim dt As New DataTable Dim ListofmyObjects As New List(Of widget_types)(obj) Dim objList As New cObjectToTable(Of widget_types)(ListofmyObjects) dt = objList.GetTable() Dim obj1 For Each obj1 In obj blPersons.Add(obj1) Next Dim col1 As New DataGridViewTextBoxColumn col1.DisplayIndex = 0 col1.DataPropertyName = "Id" col1.HeaderText = "Id" dgvi00.Columns.Add(col1) Dim col2 As New ComboColumn col2.DisplayIndex = 1 col2.SortMode = DataGridViewColumnSortMode.Automatic col2.HeaderText = "Name" col2.DataPropertyName = "Name" col2.ToolTipText = "Select something from my combo" Dim dst As New DataSet 'Dim dt1 As New DataTable 'dt1.Columns.Add(col2.HeaderText) 'For Each thing In dt.Rows ' MsgBox(thing(1).ToString) ' dt1.Rows.Add(thing(1).ToString) 'Next dst.Tables.Add(dt) col2.DataSource = dst.Tables(0) col2.DisplayMember = "Name" Me.dgvi00.Columns.AddRange(col2) dgvi00.DataSource = blPersons.BindingSource 'setup the bindings for the binding navigator Dim bn As New _365_Media_Library.BindingNavigatorWithFilter bn.Dock = DockStyle.Bottom bn.GripStyle = ToolStripGripStyle.Hidden Me.Controls.Add(bn) bn.BindingSource = blPersons.BindingSource note : its working good in standalone application regards and thanks sarva

    Read the article

  • Faster way to convert from a String to generic type T when T is a valuetype?

    - by Kumba
    Does anyone know of a fast way in VB to go from a string to a generic type T constrained to a valuetype (Of T as Structure), when I know that T will always be some number type? This is too slow for my taste: Return DirectCast(Convert.ChangeType(myStr, GetType(T)), T) But it seems to be the only sane method of getting from a String -- T. I've tried using Reflector to see how Convert.ChangeType works, and while I can convert from the String to a given number type via a hacked-up version of that code, I have no idea how to jam that type back into T so it can be returned. I'll add that part of the speed penalty I'm seeing (in a timing loop) is because the return value is getting assigned to a Nullable(Of T) value. If I strongly-type my class for a specific number type (i.e., UInt16), then I can vastly increase the performance, but then the class would need to be duplicated for each numeric type that I use. It'd almost be nice if there was converter to/from T while working on it in a generic method/class. Maybe there is and I'm oblivious to its existence?

    Read the article

  • Error while closing SQL Connection

    - by Wickedman84
    I have a problem with closing the SQLconnection in my application. My application is in VB.net. I have a reference in my application to a class with code to open and close the database connection and to execute all sql scripts. The error occurs when i close my application. In the formClosing event of my main form I call a function that closes all the connections. But just before I close the connections I perform an SQLquery to delete a row from a table with the function below. Public Function DeleteFunction(ByVal mySQLQuery As String, ByVal cmd As SqlCommand) As Boolean Try cmd.Connection = myConnection cmd.CommandText = mySQLQuery cmd.ExecuteNonQuery() Return True Catch ex As Exception WriteErrorMessage("DeleteFunction", ex, Logpath, "SQL Error: " & mySQLQuery) Return False End Try End Function In my application I check the result of the boolean. If it returns True, then i call the function to close the database connection. The returned boolean is True and the requested row is deleted in my database. This means i can close my connection which I do with the function below. Public Sub DatabaseConnClose() myCommand.CommandText = "" myConnection.Close() myCommand = Nothing myConnection = Nothing End Sub After executing this code I receive an error in my logfile from the DeleteFunction. It says: "Connection property has not been initialized." It seems very strange to receive an error from a function that was completely executed, or am i wrong to think that? Can anyone tell me why I receive this error and how I can solve the problem?

    Read the article

  • WPF DataGrid and Avalon TimePicker binding problem

    - by Jorge Vargas
    I'm using a the WPF DataGrid from the wpf toolkit and a TimePicker from AvalonControlsLibrary to insert a collection of TimeSpans. My problem is that bindings are not working inside the DataGrid, and I have no clue of why this isn't working. Here is my setup: I have the following XAML: <Window x:Class="Views.TestMainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:wpf="http://schemas.microsoft.com/wpf/2008/toolkit" xmlns:a="http://schemas.AvalonControls/AvalonControlsLibrary/Controls" SizeToContent="WidthAndHeight" MinHeight="250" MinWidth="300"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="*" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <GroupBox Grid.Row="0"> <GroupBox.Header> Testing it: </GroupBox.Header> <wpf:DataGrid ItemsSource="{Binding Path=TestSpans}" AutoGenerateColumns="False"> <wpf:DataGrid.Columns> <wpf:DataGridTemplateColumn Header="Start"> <wpf:DataGridTemplateColumn.CellEditingTemplate> <DataTemplate> <a:TimePicker SelectedTime="{Binding Path=., Mode=TwoWay}" /> </DataTemplate> </wpf:DataGridTemplateColumn.CellEditingTemplate> <wpf:DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding}" /> </DataTemplate> </wpf:DataGridTemplateColumn.CellTemplate> </wpf:DataGridTemplateColumn> </wpf:DataGrid.Columns> </wpf:DataGrid> </GroupBox> <StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Grid.Row="1"> <a:TimePicker SelectedTime="{Binding Path=SelectedTime, Mode=TwoWay}" /> </StackPanel> </Grid> And this is my ViewModel: Imports System.Collections.ObjectModel Namespace ViewModels Public Class TestMainWindowViewModel Private _selectedTime As TimeSpan = DateTime.Now.TimeOfDay Public Property SelectedTime() As TimeSpan Get Return _selectedTime End Get Set(ByVal value As TimeSpan) _selectedTime = value End Set End Property Private _testSpans As ObservableCollection(Of TimeSpan) = New ObservableCollection(Of TimeSpan) Public Property TestSpans() As ObservableCollection(Of TimeSpan) Get Return _testSpans End Get Set(ByVal value As ObservableCollection(Of TimeSpan)) _testSpans = value End Set End Property Public Sub New() _testSpans.Add(DateTime.Now.TimeOfDay) _testSpans.Add(DateTime.Now.TimeOfDay) _testSpans.Add(DateTime.Now.TimeOfDay) End Sub End Class End Namespace I'm starting this window in application.xaml.vb like this: Class Application ' Application-level events, such as Startup, Exit, and DispatcherUnhandledException ' can be handled in this file. Protected Overrides Sub OnStartup(ByVal e As System.Windows.StartupEventArgs) MyBase.OnStartup(e) Dim window As Views.TestMainWindow = New Views.TestMainWindow window.DataContext = New TestMainWindowViewModel() window.Show() End Sub End Class

    Read the article

  • Problem with FedEx Address validation web service

    - by DJ Matthews
    Hi, I'm trying to get started with Fedex'es Address validation service and I'm running into a road block with FedEx's own demo application. This is the code in there app: Sub Main() ''# Build a AddressValidationRequest object Dim request As AddressValidationRequest = New AddressValidationRequest() Console.WriteLine("--- Setting Credentials ---") request.WebAuthenticationDetail = New WebAuthenticationDetail() request.WebAuthenticationDetail.UserCredential = New WebAuthenticationCredential() request.WebAuthenticationDetail.UserCredential.Key = "###" ''# Replace "XXX" with the Key request.WebAuthenticationDetail.UserCredential.Password = "###" ''# Replace "XXX" with the Password Console.WriteLine("--- Setting Account Information ---") request.ClientDetail = New ClientDetail() request.ClientDetail.AccountNumber = "###" ''# Replace "XXX" with clients account number request.ClientDetail.MeterNumber = "###" ''# Replace "XXX" with clients meter number request.TransactionDetail = New TransactionDetail() request.TransactionDetail.CustomerTransactionId = "Address Validation v2 Request using VB.NET Sample Code" ''# This is just an echo back request.Version = New VersionId() request.RequestTimestamp = DateTime.Now Console.WriteLine("--- Setting Validation Options ---") request.Options = New AddressValidationOptions() request.Options.CheckResidentialStatus = True request.Options.MaximumNumberOfMatches = 5 request.Options.StreetAccuracy = AddressValidationAccuracyType.LOOSE request.Options.DirectionalAccuracy = AddressValidationAccuracyType.LOOSE request.Options.CompanyNameAccuracy = AddressValidationAccuracyType.LOOSE request.Options.ConvertToUpperCase = True request.Options.RecognizeAlternateCityNames = True request.Options.ReturnParsedElements = True Console.WriteLine("--- Address 1 ---") request.AddressesToValidate = New AddressToValidate(1) {New AddressToValidate(), New AddressToValidate()} request.AddressesToValidate(0).AddressId = "WTC" request.AddressesToValidate(0).Address = New Address() request.AddressesToValidate(0).Address.StreetLines = New String(0) {"10 FedEx Parkway"} request.AddressesToValidate(0).Address.PostalCode = "38017" request.AddressesToValidate(0).CompanyName = "FedEx Services" Console.WriteLine("--- Address 2 ---") request.AddressesToValidate(1).AddressId = "Kinkos" request.AddressesToValidate(1).Address = New Address() request.AddressesToValidate(1).Address.StreetLines = New String(0) {"50 N Front St"} request.AddressesToValidate(1).Address.PostalCode = "38103" request.AddressesToValidate(1).CompanyName = "FedEx Kinkos" Dim addressValidationService As AddressValidationService.AddressValidationService = New AddressValidationService.AddressValidationService ''# Try ''# This is the call to the web service passing in a AddressValidationRequest and returning a AddressValidationReply Console.WriteLine("--- Sending Request..... ---") Dim reply As New AddressValidationReply() reply = addressValidationService.addressValidation(request) Console.WriteLine("--- Processing request.... ---") ''#This is where I get the error If (Not reply.HighestSeverity = NotificationSeverityType.ERROR) And (Not reply.HighestSeverity = NotificationSeverityType.FAILURE) Then If (Not reply.AddressResults Is Nothing) Then For Each result As AddressValidationResult In reply.AddressResults Console.WriteLine("Address Id - " + result.AddressId) Console.WriteLine("--- Proposed Details ---") If (Not result.ProposedAddressDetails Is Nothing) Then For Each detail As ProposedAddressDetail In result.ProposedAddressDetails Console.WriteLine("Score - " + detail.Score) Console.WriteLine("Address - " + detail.Address.StreetLines(0)) Console.WriteLine(" " + detail.Address.StateOrProvinceCode + " " + detail.Address.PostalCode + " " + detail.Address.CountryCode) Console.WriteLine("Changes -") For Each change As AddressValidationChangeType In detail.Changes Console.WriteLine(change.ToString()) Next Console.WriteLine("") Next End If Console.WriteLine("") Next End If Else For Each notification As Notification In reply.Notifications Console.WriteLine(notification.Message) Next End If Catch e As SoapException Console.WriteLine(e.Detail.InnerText) Catch e As Exception Console.WriteLine(e.Message) End Try Console.WriteLine("Press any key to quit !") Console.ReadKey() End Sub It seems to send the request object to the web service, but the"reply" object is returned with "Nothing". I could understand if I wrote the code, but good god... they can't even get their own code to work? Has anyone else seen/fixed this problem?

    Read the article

  • Telerik Object reference not set to an instance of an object

    - by Duncan
    Hi, I have a main form which contains multiple worker threads. These threads raise events which update Telerik controls on the main form. The event handlers contain code which check if InvokeRequired and BeginInvoke where required. At random interval I am receiving the following exception, and have no idea on how where to find this? I was wondering if the following is understandable to anyone to point me in the right direction. Thanks in advance System.Reflection.TargetInvocationException was unhandled Message="Exception has been thrown by the target of an invocation." Source="mscorlib" StackTrace: at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks) at System.Delegate.DynamicInvokeImpl(Object[] args) at System.Windows.Forms.Control.InvokeMarshaledCallbackDo(ThreadMethodEntry tme) at System.Windows.Forms.Control.InvokeMarshaledCallbackHelper(Object obj) at System.Threading.ExecutionContext.runTryCode(Object userData) at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Windows.Forms.Control.InvokeMarshaledCallback(ThreadMethodEntry tme) at System.Windows.Forms.Control.InvokeMarshaledCallbacks() at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ScrollableControl.WndProc(Message& m) at Telerik.WinControls.RadControl.WndProc(Message& m) at Telerik.WinControls.UI.RadStatusStrip.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.Run(ApplicationContext context) at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun() at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel() at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine) at MyFX.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81 at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() InnerException: System.NullReferenceException Message="Object reference not set to an instance of an object." Source="Telerik.WinControls" StackTrace: at Telerik.WinControls.Layouts.ContextLayoutManager.LayoutQueue.RemoveOrphans(RadElement parent) at Telerik.WinControls.Layouts.ContextLayoutManager.LayoutQueue.Add(RadElement e) at Telerik.WinControls.RadElement.InvalidateArrange(Boolean recursive) at Telerik.WinControls.RadElement.InvalidateArrange() at Telerik.WinControls.RadElement.Measure(SizeF availableSize) at Telerik.WinControls.Layouts.ImageAndTextLayoutPanel.MeasureOverride(SizeF availableSize) at Telerik.WinControls.RadElement.MeasureCore(SizeF availableSize) at Telerik.WinControls.RadElement.Measure(SizeF availableSize) at Telerik.WinControls.Layouts.ContextLayoutManager.UpdateLayout() at Telerik.WinControls.Layouts.ContextLayoutManager.UpdateLayoutCallback(ILayoutManager manager)

    Read the article

  • Problems upgrading VB.Net 2008 project into VS2010

    - by Brett Rigby
    Hi there, I have been upgrading several different VS2008 projects into VS2010 and have found a problem with VB.Net projects when they are converted. Once converted, the .vbproj files have changed from this in VS2008: <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <DefineDebug>true</DefineDebug> <DefineTrace>true</DefineTrace> <OutputPath>bin\Debug\</OutputPath> <DocumentationFile>CustomerManager.xml</DocumentationFile> <WarningsAsErrors>41999,42016,42017,42018,42019,42020,42021,42022,42032,42036</WarningsAsErrors> </PropertyGroup> To this in VS2010: <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <DefineDebug>true</DefineDebug> <DefineTrace>true</DefineTrace> <OutputPath>bin\Debug\</OutputPath> <DocumentationFile>CustomerManager.xml</DocumentationFile> <NoWarn>42353,42354,42355</NoWarn> <WarningsAsErrors>41999,42016,42017,42018,42019,42020,42021,42022,42032,42036</WarningsAsErrors> </PropertyGroup> The main difference, is that in the VS2010 version, the 42353,42354,42355 value has been added; Inside the IDE, this manifests itself as the following setting in the Project Properties | Compile section as: "Function returning intrinsic value type without return value" = None This isn't a problem when building code inside Visual Studio 2010, but when trying to build the code through our continuous integration scripts, it fails with the following errors: [msbuild] vbc : Command line error BC2026: warning number '42353' for the option 'nowarn' is either not configurable or not valid [msbuild] vbc : Command line error BC2026: warning number '42354' for the option 'nowarn' is either not configurable or not valid [msbuild] vbc : Command line error BC2026: warning number '42355' for the option 'nowarn' is either not configurable or not valid I couldn't find anything on Google for these messages, which is strange, as I am trying to find out why this is happening. Any suggestions as to why Visual Studio 2010's conversion wizard is doing this?

    Read the article

  • Slow performance when utilizing Interop.DSOFile to search files by Custom Document Property

    - by Gradatc
    I am new to the world of VB.NET and have been tasked to put together a little program to search a directory of about 2000 Excel spreadsheets and put together a list to display based on the value of a Custom Document Property within that spreadsheet file. Given that I am far from a computer programmer by education or trade, this has been an adventure. I've gotten it to work, the results are fine. The problem is, it takes well over a minute to run. It is being run over a LAN connection. When I run it locally (using a 'test' directory of about 300 files) it executes in about 4 seconds. I'm not sure even what to expect as a reasonable execution speed, so I thought I would ask here. The code is below, if anyone thinks changes there might be of use in speeding things up. Thank you in advance! Private Sub listByPt() Dim di As New IO.DirectoryInfo(dir_loc) Dim aryFiles As IO.FileInfo() = di.GetFiles("*" & ext_to_check) Dim fi As IO.FileInfo Dim dso As DSOFile.OleDocumentProperties Dim sfilename As String Dim sheetInfo As Object Dim sfileCount As String Dim ifilesDone As Integer Dim errorList As New ArrayList() Dim ErrorFile As Object Dim ErrorMessage As String 'Initialize progress bar values ifilesDone = 0 sfileCount = di.GetFiles("*" & ext_to_check).Length Me.lblHighProgress.Text = sfileCount Me.lblLowProgress.Text = 0 With Me.progressMain .Maximum = di.GetFiles("*" & ext_to_check).Length .Minimum = 0 .Value = 0 End With 'Loop through all files in the search directory For Each fi In aryFiles dso = New DSOFile.OleDocumentProperties sfilename = fi.FullName Try dso.Open(sfilename, True) 'grab the PT Initials off of the logsheet Catch excep As Runtime.InteropServices.COMException errorList.Add(sfilename) End Try Try sheetInfo = dso.CustomProperties("PTNameChecker").Value Catch ex As Runtime.InteropServices.COMException sheetInfo = "NONE" End Try 'Check to see if the initials on the log sheet 'match those we are searching for If sheetInfo = lstInitials.SelectedValue Then Dim logsheet As New LogSheet logsheet.PTInitials = sheetInfo logsheet.FileName = sfilename PTFiles.Add(logsheet) End If 'update progress bar Me.progressMain.Increment(1) ifilesDone = ifilesDone + 1 lblLowProgress.Text = ifilesDone dso.Close() Next lstResults.Items.Clear() 'loop through results in the PTFiles list 'add results to the listbox, removing the path info For Each showsheet As LogSheet In PTFiles lstResults.Items.Add(Path.GetFileNameWithoutExtension(showsheet.FileName)) Next 'build error message to display to user ErrorMessage = "" For Each ErrorFile In errorList ErrorMessage += ErrorFile & vbCrLf Next MsgBox("The following Log Sheets were unable to be checked" _ & vbCrLf & ErrorMessage) PTFiles.Clear() 'empty PTFiles for next use End Sub

    Read the article

  • Global Entity Framework Context in WPF Application

    - by OffApps Cory
    Good day, I am in the middle of development of a WPF application that is using Entity Framework (.NET 3.5). It accesses the entities in several places throughout. I am worried about consistency throughout the application in regard to the entities. Should I be instancing separate contexts in my different views, or should I (and is a a good way to do this) instance a single context that can be accessed globally? For instance, my entity model has three sections, Shipments (with child packages and further child contents), Companies/Contacts (with child addresses and telephones), and disk specs. The Shipments and EditShipment views access the DiskSpecs, and the OptionsView manages the DiskSpecs (Create, Edit, Delete). If I edit a DiskSpec, I have to have something in the ShipmentsView to retrieve the latest specs if I have separate contexts right? If it is safe to have one overall context from which the rest of the app retrieves it's objects, then I imagine that is the way to go. If so, where would that instance be put? I am using VB.NET, but I can translate from C# pretty good. Any help would be appreciated. I just don't want one of those applications where the user has to hit reload a dozen times in different parts of the app to get the new data. Update: OK so I have changed my app as follows: All contexts are created in Using Blocks to dispose of them after they are no longer needed. When loaded, all entities are detatched from context before it is disposed. A new property in the MainViewModel (ContextUpdated) raises an event that all of the other ViewModels subscribe to which runs that ViewModels RefreshEntities method. After implementing this, I started getting errors saying that an entity can only be referenced by one ChangeTracker at a time. Since I could not figure out which context was still referencing the entity (shouldn't be any context right?) I cast the object as IEntityWithChangeTracker, and set SetChangeTracker to nothing (Null). This has let to the current problem: When I Null the changeTracker on the Entity, and then attach it to a context, it loses it's changed state and does not get updated to the database. However if I do not null the change tracker, I can't attach. I have my own change tracking code, so that is not a problem. My new question is, how are you supposed to do this. A good example Entity query and entity save code snipped would go a long way, cause I am beating my head in trying to get what I once thought was a simple transaction to work. Any help would elevate you to near god-hood.

    Read the article

  • StructureMap Autowiring with two different instances of the same interface

    - by Lambda
    For the last two days, i tried my best to learn something about StructureMap, using an old project of mine as an concrete implementation example. I tried to simplify my question as much as possible. While i will post my examples in vb.net, answers with examples in C# are also okay. The project includes an interfaces called IDatabase which connects itself to a Database. The important part looks like this. Public Interface IDatabase Function Connect(ByVal ConnectionSettings As ConnectionSettings) As Boolean ReadOnly Property ConnectionOpen As Boolean [... more functions...] End Interface Public Class MSSQLConnection Implements IDatabase Public Function Connect(ByVal ConnectionSettings As ConnectionSettings) As Boolean Implements IDatabase.Connect [... Implementation ...] End Function [... more implementations...] End Class ConnectionSettings is a structure that has all the information needed to connect to a Database. I want to open the Database Connection once and use it for every single connection in the project, so i register a instance in the ObjectFactory. dim foo = ObjectFactory.GetInstance(Of MSSQLConnection)() dim bar as ConnectionSettings foo.connect(bar) ObjectFactory.Configure(Sub(x) x.For(Of IDatabase).Use(foo)) Up until this part, everything works like a charm. Now, i get to a point where i hav e classes that need an additional instance of IDatabase because they connect to a second database. Public Class ExampleClass Public Sub New(ByVal SameOldDatabase as IDatabase, ByVal NewDatabase as IDatabase) [...] Magic happens here [...] End Sub End Class I want this second IDatabase to behave much like the first one. I want it to use a concrete, single instance and want to connect it to a different database invoking Connect with a different ConnectionSettings. The problem is: While i'm pretty sure it's somewhow possible, (my initial idea was registering ExampleClass with alternative constructor arguments), i actually want to do it without registering ExampleClass. This probably involves more configuration, but i have no idea how to do it. So, basically, it comes down to this question: How do i configurate the ObjectFactory in a way that the autowiring always invokes the constructor with object Database1 for the first IDatabase parameter and object Database2 for the second one (if there is one?)

    Read the article

  • How should I provide access to this custom DAL?

    - by Casey
    I'm writing a custom DAL (VB.NET) for an ordering system project. I'd like to explain how it is coded now, and receive some alternate ideas to make coding against the DAL easier/more readable. The DAL is part of an n-tier (not n-layer) application, where each tier is in it's own assembly/DLL. The DAL consists of several classes that have specific behavior. For instance, there is an Order class that is responsible for retrieving and saving orders. Most of the classes have only two methods, a "Get" and a "Save," with multiple overloads for each. These classes are marked as Friend and are only visible to the DAL (which is in it's own assembly). In most cases, the DAL returns what I will call a "Data Object." This object is a class that contains only data and validation, and is located in a common assembly that both the BLL and DAL can read. To provide public access to the DAL, I currently have a static (module) class that has many shared members. A simplified version looks something like this: Public Class DAL Private Sub New End Sub Public Shared Function GetOrder(OrderID as String) as OrderData Dim OrderGetter as New OrderClass Return OrderGetter.GetOrder(OrderID) End Function End Class Friend Class OrderClass Friend Function GetOrder(OrderID as string) as OrderData End Function End Class The BLL would call for an order like this: DAL.GetOrder("123456") As you can imagine, this gets cumbersome very quickly. I'm mainly interested in structuring access to the DAL so that Intellisense is very intuitive. As it stands now, there are too many methods/functions in the DAL class with similar names. One idea I had is to break down the DAL into nested classes: Public Class DAL Private Sub New End Sub Public Class Orders Private Sub New End Sub Public Shared Function Get(OrderID as string) as OrderData End Function End Class End Class So the BLL would call like this: DAL.Orders.Get("12345") This cleans it up a bit, but it leaves a lot of classes that only have references to other classes, which I don't like for some reason. Without resorting to passing DB specific instructions (like where clauses) from BLL to DAL, what is the best or most common practice for providing a single point of access for the DAL?

    Read the article

  • AD - DirectoryServices: VBNET2.0 - Speaking architecture...

    - by Will Marcouiller
    I've been mandated to write an application to migrate the Active Directory access models to another environment. Here's the context: I'm stuck with VB.NET 2005 and .NET Framework 2.0; The application must use the Windows authenticated user to manage AD; The objects I have to handle are Groups, Users and OrganizationalUnits; I intend to use the Façade design pattern to provider ease of use and a fully reusable code; I plan to write a factory for each of the objects managed (group, ou, user); The use of Attributes should be useful here, I guess; As everything is about the DirectoryEntry class when accessing the AD, it seems a good candidate for generic types. Obligatory features: User creates new OUs manually; User creates new group manually; User creates new user (these users are services accounts) manually; Application reads an XML file which contains the OUs, groups and users to create; Application informs the user about the OUs, groups and users that shall be created; User specifies the domain environment where to migrate the XML input file designated objects; User makes changes if needed, and launches the task operations; Application performs required by the XML input file operations against the underlying AD as specified by the user; Application informs the user upon completion. Linear features: User fetches OUs, groups, users; User changes OUs, groups, users; User deletes OUs, groups, users; The application logs AD entries and operations performed, plus errors and exceptions; Nice-to-have features: Application rollbacks operations on error or exception. I've been working for weeks now to get acquainted with the AD and the System.DirectoryServices assembly. But I don't seem to find a way to be fully satisfied with what I'm doing and always looking for better. I have studied Bret de Smet's Linq to AD on CodePlex, but then again, I can't use it as I'm stuck with .NET 2.0, so no Linq! But I've learned about Attributes, and seen that he's working with generic types as he codes a DirectorySource class to perform the operations for OUs, groups and users. Any suggestions? Thanks for any help, code sample, ideas, architural solution, everything!

    Read the article

  • ASP.net Repeater Control Problem (nothing outputted)

    - by Phil
    I have the following db code in my usercontrol (content.ascx.vb): If did = 0 Then s = "select etc (statement works on server)" x = New SqlCommand(s, c) x.Parameters.Add("@contentid", Data.SqlDbType.Int) x.Parameters("@contentid").Value = contentid c.Open() r = x.ExecuteReader If r.HasRows Then Contactinforepeater.DataSource = r End If c.Close() r.Close() Else s = "select etc (statement works on server)" x = New SqlCommand(s, c) x.Parameters.Add("@contentid", SqlDbType.Int) x.Parameters("@contentid").Value = contentid x.Parameters.Add("@did", SqlDbType.Int) x.Parameters("@did").Value = did c.Open() r = x.ExecuteReader If r.HasRows Then Contactinforepeater.DataSource = r c.Close() r.Close() End If End If Then I have the following repeater control markup in my usercontrol (content.ascx): <asp:Repeater ID="Contactinforepeater" runat="server"> <HeaderTemplate> <h1>Contact Information</h1> </HeaderTemplate> <ItemTemplate> <table width="50%"> <tr> <td colspan="2"><%#Container.DataItem("position")%></td> </tr> <tr> <td>Name:</td> <td><%#Container.DataItem("surname")%></td> </tr> <tr> <td>Telephone:</td> <td><%#Container.DataItem("telephone")%></td> </tr> <tr> <td>Fax:</td> <td><%#Container.DataItem("fax")%></td> </tr> <tr> <td>Email:</td> <td><%#Container.DataItem("email")%></td> </tr> </table> </ItemTemplate> <SeparatorTemplate><br /><hr /><br /></SeparatorTemplate> </asp:Repeater> When I insert this usercontrol into default.aspx with this code: <%@ Register src="Modules/Content.ascx" tagname="Content" tagprefix="uc1" %> and <form id="form1" runat="server"> <div> <uc1:Content ID="Content" runat="server" /> </div> </form> I do not get any error messages but the expected content from the database is not displayed. Can someone please show me the syntax to get this working or point out where I am going wrong? Thanks in advance!

    Read the article

  • Linking buttion to jQuery through service

    - by Ruddy
    I have a small problem that should be very easy to overcome. For some reason I cant work this out. So the problem is I cannot get a button to link to some jquery. My set-up is as follows (showing the relevant code): Default.aspx jQuery: function getContent() { var data = { numberID: 1 }; $.jsonAspNet("ContentService.asmx", "GetContent", data, function (result) { $('#content').html(result); }); } jQuery(document).ready(function () { getContent(); } HTML: <div id="content"></div> ContentService.vb Public Function GetContent(number As Integer) As String Dim sb = New StringBuilder sb.AppendLine("<table>") sb.AppendLine("<tr>") sb.AppendLine("<td class='ui-widget-header ui-corner-all'>Number</td>") sb.AppendLine("</tr>") sb.AppendLine("<tr>") sb.AppendLine("<td>" & number & "</td>") sb.AppendLine("<td><a href='#' id='test' class='fg-button ui-state-default ui-corner-all'><img src='" & Context.Request.ApplicationPath & "/images/spacer.gif' class='ui-icon ui-icon-pencil' /></a></td>") sb.AppendLine("</tr>") sb.AppendLine("</table>") Return sb.ToString End Function So that's the basics of what I have everything works but I'm not sure how to get the button (id='test') to get linked to some jQuery. I want it to be pressed and bring up a popup. I have tried to put the jQuery on default.aspx but this doesn't seem to work unless the button is place in the HTML on that page. $('#test').unbind('click').click(function () { alert('Working'); }); I'm sure this is easy to be able to do but I have been trying for a while and cannot seem to get it to work.

    Read the article

  • AD-DirectoryServices: .NET2.0 - Speaking architecture, approach and best practices... Suggestions?

    - by Will Marcouiller
    I've been mandated to write an application to migrate the Active Directory access models to another environment. Here's the context: I'm stuck with VB.NET 2005 and .NET Framework 2.0; The application must use the Windows authenticated user to manage AD; The objects I have to handle are Groups, Users and OrganizationalUnits; I intend to use the Façade design pattern to provider ease of use and a fully reusable code; I plan to write a factory for each of the objects managed (group, ou, user); The use of Attributes should be useful here, I guess; As everything is about the DirectoryEntry class when accessing the AD, it seems a good candidate for generic types. Obligatory features: User creates new OUs manually; User creates new group manually; User creates new user (these users are services accounts) manually; Application reads an XML file which contains the OUs, groups and users to create; Application informs the user about the OUs, groups and users that shall be created; User specifies the domain environment where to migrate the XML input file designated objects; User makes changes if needed, and launches the task operations; Application performs required by the XML input file operations against the underlying AD as specified by the user; Application informs the user upon completion. Linear features: User fetches OUs, groups, users; User changes OUs, groups, users; User deletes OUs, groups, users; The application logs AD entries and operations performed, plus errors and exceptions; Nice-to-have features: Application rollbacks operations on error or exception. I've been working for weeks now to get acquainted with the AD and the System.DirectoryServices assembly. But I don't seem to find a way to be fully satisfied with what I'm doing and always looking for better. I have studied Bret de Smet's Linq to AD on CodePlex, but then again, I can't use it as I'm stuck with .NET 2.0, so no Linq! But I've learned about Attributes, and seen that he's working with generic types as he codes a DirectorySource class to perform the operations for OUs, groups and users. I have been able to add groups to the AD; I have been able to add users to the AD; The created user is automatically disabled? I seem to get confused with the use of a LDAP path to add objects. For instance, one needs two instances of a System.DirectoryServices.DirectoryEntry class to add a group, for instance. Why this? Any suggestions? Thanks for any help, code sample, ideas, architural solution, everything!

    Read the article

  • ASP.net Repeater Control Problem (nothing outputted from datasource(sqldatareader))

    - by Phil
    I have the following code to get the repeaters' data in my usercontrol (content.ascx.vb): If did = 0 Then s = "select etc (statement works on server)" x = New SqlCommand(s, c) x.Parameters.Add("@contentid", Data.SqlDbType.Int) x.Parameters("@contentid").Value = contentid c.Open() r = x.ExecuteReader If r.HasRows Then Contactinforepeater.DataSource = r End If c.Close() r.Close() Else s = "select etc (statement works on server)" x = New SqlCommand(s, c) x.Parameters.Add("@contentid", SqlDbType.Int) x.Parameters("@contentid").Value = contentid x.Parameters.Add("@did", SqlDbType.Int) x.Parameters("@did").Value = did c.Open() r = x.ExecuteReader If r.HasRows Then Contactinforepeater.DataSource = r c.Close() r.Close() End If End If Then I have the following repeater control markup in my usercontrol (content.ascx): <asp:Repeater ID="Contactinforepeater" runat="server"> <HeaderTemplate> <h1>Contact Information</h1> </HeaderTemplate> <ItemTemplate> <table width="50%"> <tr> <td colspan="2"><%#Container.DataItem("position")%></td> </tr> <tr> <td>Name:</td> <td><%#Container.DataItem("surname")%></td> </tr> <tr> <td>Telephone:</td> <td><%#Container.DataItem("telephone")%></td> </tr> <tr> <td>Fax:</td> <td><%#Container.DataItem("fax")%></td> </tr> <tr> <td>Email:</td> <td><%#Container.DataItem("email")%></td> </tr> </table> </ItemTemplate> <SeparatorTemplate><br /><hr /><br /></SeparatorTemplate> </asp:Repeater> When I insert this usercontrol into default.aspx with this code: <%@ Register src="Modules/Content.ascx" tagname="Content" tagprefix="uc1" %> and <form id="form1" runat="server"> <div> <uc1:Content ID="Content" runat="server" /> </div> </form> I do not get any error messages but the expected content from the database is not displayed. Can someone please show me the syntax to get this working or point out where I am going wrong? Thanks in advance!

    Read the article

  • How to assign class property as display data member in datagridview

    - by KoolKabin
    hi guys, I am trying to display my data in datagridview. I created a class with different property and used its list as the datasource. it worked fine. but I got confused how to do that in case we have nested class. My Classes are as follows: class Category property UIN as integer property Name as string end class class item property uin as integer property name as string property mycategory as category end class my data list as follows: dim myDataList as list(of Item) = new List(of Item) myDataList.Add(new Item(1,"item1",new category(1,"cat1"))) myDataList.Add(new Item(2,"item2",new category(1,"cat1"))) myDataList.Add(new Item(3,"item3",new category(1,"cat1"))) myDataList.Add(new Item(4,"item4",new category(2,"cat2"))) myDataList.Add(new Item(5,"item5",new category(2,"cat2"))) myDataList.Add(new Item(6,"item6",new category(2,"cat2"))) Now I binded the datagridview control like: DGVMain.AutoGenerateColumns = False DGVMain.ColumnCount = 3 DGVMain.Columns(0).DataPropertyName = "UIN" DGVMain.Columns(0).HeaderText = "ID" DGVMain.Columns(1).DataPropertyName = "Name" DGVMain.Columns(1).HeaderText = "Name" DGVMain.Columns(2).DataPropertyName = "" **'here i want my category name** DGVMain.Columns(2).HeaderText = "category" DGVMain.datasource = myDataList DGVMain.refresh() I have tried using mycategory.name but it didn't worked. What can be done to get expected result? Is there any better idea other than this to accomplish the same task? Edited My question as per comment: I have checked the link given by u. It was nice n very usefull. Since the code was in c# i tried to convert it in vb. Everything went good but failed at a point of case sensitive and next one is that i had my nested class name itemcategory and my property name was category. there it arouse the problem. it didn't searched for category but it searched for itemcategory. so confused on it. My Code as follows: Private Sub DGVMain_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DGVMain.CellFormatting Dim DGVMain As DataGridView = CType(sender, DataGridView) e.Value = EvaluateValue(DGVMain.Rows(e.RowIndex).DataBoundItem, DGVMain.Columns(e.ColumnIndex).DataPropertyName) End Sub Private Function EvaluateValue(ByRef myObj As Object, ByRef myProp As String) As String Dim Ret As String = "" Dim Props As System.Reflection.PropertyInfo() Dim PropA As System.Reflection.PropertyInfo Dim ObjA As Object If myProp.Contains(".") Then myProp = myProp.Substring(0, myProp.IndexOf(".")) Props = myObj.GetType().GetProperties() For Each PropA In Props ObjA = PropA.GetValue(myObj, New Object() {}) If ObjA.GetType().Name = myProp Then Ret = EvaluateValue(ObjA, myProp.Substring(myProp.IndexOf(".") + 1)) Exit For End If Next Else PropA = myObj.GetType().GetProperty(myProp) Ret = PropA.GetValue(myObj, New Object() {}).ToString() End If Return Ret End Function

    Read the article

  • Invalid cast exception

    - by user127147
    I have a simple application to store address details and edit them. I have been away from VB for a few years now and need to refreash my knowledge while working to a tight deadline. I have a general Sub responsible for displaying a form where user can add contact details (by pressing button add) and edit them (by pressing button edit). This sub is stored in a class Contact. The way it is supposed to work is that there is a list with all the contacts and when new contact is added a new entry is displayed. If user wants to edit given entry he or she selects it and presses edit button Public Sub Display() Dim C As New Contact C.Cont = InputBox("Enter a title for this contact.") C.Fname = frmAddCont.txtFName.Text C.Surname = frmAddCont.txtSName.Text C.Address = frmAddCont.txtAddress.Text frmStart.lstContact.Items.Add(C.Cont.ToString) End Sub I call it from the form responsible for adding new contacts by Dim C As New Contact C.Display() and it works just fine. However when I try to do something similar using the edit button I get errors - "Unable to cast object of type 'System.String' to type 'AddressBook.Contact'." Dim C As Contact If lstContact.SelectedItem IsNot Nothing Then C = lstContact.SelectedItem() C.Display() End If I think it may be something simple however I wasn't able to fix it and given short time I have I decided to ask for help here. I have updated my class with advice from other members and here is the final version (there are some problems however). When I click on the edit button it displays only the input box for the title of the contact and actually adds another entry in the list with previous data for first name, second name etc. Public Class Contact Public Contact 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 Sub NewContact() FName = frmAddCont.txtFName.ToString frmStart.lstContact.Items.Add(FName) frmAddCont.Hide() End Sub Public Sub Display() Dim C As New Contact C.Cont = InputBox("Enter a title for this contact.") C.Fname = frmAddCont.txtFName.Text C.Surname = frmAddCont.txtSName.Text C.Address = frmAddCont.txtAddress.Text 'frmStart.lstContact.Items.Add(C.Cont.ToString) frmStart.lstContact.Items.Add(C) End Sub End Class

    Read the article

  • how to create a system-wide independent universal counter object primarily for Database keys?

    - by andora
    I would like to create/use a system-wide independent universal 'counter object' that can be called via COM in a thread-safe manner. The counter object will be passed an ID to identify which counter to return, handle the counting, 'persist' the count (occasionally), have reasonable performance (as fast as possible) perhaps capable of 1000 counts per second or better (1mS) and be accessible cross-process/out-of-process. The current count status must be persisted between object restarts/shutdowns. The counter object is liklely to be a 'singleton' type object implemented in some form of free-threaded dictionary, containing maybe 10 counters (perhaps 50 max). The count needs to be monotonic and consistent, (ie: guaranteed unique sequential values). Each counter should have a few methods, like reset, inc, dec, set, clear, remove. As a luxury, I would like to have a variable-increment (ie: 'step by' value). To support thread-safefty, perhaps some sorm of critical-section or mutex call. It just needs to return a long/4byte signed integer. I really want something that can be called from anywhere, including VBScript, so I figure COM is my preferred solution. The primary use of this is for database keys. I am unable to use autoinc or guid type keys and have ruled out database-generated counting systems at this point. I've spent days researching this and I have really struggled to find a solution. The best I can find is a free-threaded dictionary object that can be instantiated using COM+ from Motobit - it seems to offer all the 'basics' and I guess I could create some form of wrapper for this. So, here are my questions: Does such a 'general purpose counter-object already exist? Can you direct me to it? (MS did do an IIS/ASP object called 'MSWC.Counter' but this isn't 'cross-process'/ out-of-process component and isn't thread-safe. (but if it was, it would do!) What is the best way of creating such a Component? (I'd prefer VB6 right-now, [don't ask!] but can do in VB.NET2005 if I had to). I don't have the skills/knowledge/tools to use anything else. I am desparate for a workable solution. I need specific guidance! If anybody can code something up for me I am prepared to pay for it.

    Read the article

  • List of checkboxes

    - by Andrea Girardi
    Hi all, Happy New Year to all. I'm a newbie in VB.NET and ASP.NET. This is my problem: I retrieve a list of records from DB and, for every row, I need to show 4 checkboxes. I can use a checkboxlist for every rows, but it's not so clear how I can process the results after the submit. I've some object and some operations available for that object. From database I extract a list of object with all operations. For every operation I want to show a check box to enable or disable the operation. The result is something like that: OBJ1 - url - [] [x] [] OBJ2 - url - [] [x] [x] On url I've an href to another page created using the Id retrieved from DB. To create that I used this code: <td class="column-filename"> <strong> <asp:Label runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "GroupName")%>'></asp:Label> </strong> </td> <td align="left"> <span style="vertical-align:middle"> <asp:CheckBoxList runat="server" ID="operations" RepeatDirection="Horizontal" RepeatLayout="Table"> <asp:ListItem Text="View"></asp:ListItem> <asp:ListItem Text="Upload"></asp:ListItem> <asp:ListItem Text="Move"></asp:ListItem> <asp:ListItem Text="Delete"></asp:ListItem> <asp:ListItem Text="Rename"></asp:ListItem> <asp:ListItem Text="Replace"></asp:ListItem> </asp:CheckBoxList> </span> </td> </asp> </asp> my problem is: how can I parse all checkboxes? could you help me or send me a link or any other resources to solve my issue? many thanks! Andrea

    Read the article

  • Need help helping in converting jquery, ajax, json and asp.net

    - by Haja Mohaideen
    I am tying out this tutorial, http://www.ezzylearning.com/tutorial.aspx?tid=5869127. It works perfectly. What I am now trying to do is to host the aspx contents as html file. This html file is hosted on my wampserver which is on my laptop. The asp.net code hosted on my test server. When I try to access, I get the following error, Resource interpreted as Script but transferred with MIME type text/html: "http://201.x.x.x/testAjax/Default.aspx/AddProductToCart?callback=jQuery17103264484549872577_1346923699990&{%20pID:%20%226765%22,%20qty:%20%22100%22,%20lblType:%20%2220%22%20}&_=1346923704482". jquery.min.js:4 Uncaught SyntaxError: Unexpected token < I am not sure how to solve this problem. index.html code $(function () { $('#btnAddToCart').click(function () { var result = $.ajax({ type: "POST", url: "http://202.161.45.124/testAjax/Default.aspx/AddProductToCart", crossDomain: true, data: '{ pID: "6765", qty: "100", lblType: "20" }', contentType: "application/json; charset=utf-8", dataType: "jsonp", success: succeeded, failure: function (msg) { alert(msg); }, error: function (xhr, err) { alert(err); } }); }); }); function succeeded(msg) { alert(msg.d); } function btnAddToCart_onclick() { } </script> </head> <body> <form name="form1" method="post"> <div> <input type="button" id="btnAddToCart" onclick="return btnAddToCart_onclick()" value="Button" /> </div> </form> aspx.vb Imports System.Web.Services Imports System.Web.Script.Services <ScriptService()> Public Class WebForm1 Inherits Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Session("test") = "" End Sub <WebMethod()> <ScriptMethod(UseHttpGet:=False, ResponseFormat:=ResponseFormat.Json)> Public Shared Function AddProductToCart(pID As String, qty As String, lblType As String) As String Dim selectedProduct As String = String.Format("+ {0} - {1} - {2}", pID, qty, lblType) HttpContext.Current.Session("test") += selectedProduct Return HttpContext.Current.Session("test").ToString() End Function End Class

    Read the article

  • Visual Basic Cryptography Question

    - by Glenn Sullivan
    I am trying to mimic the results of some C code that uses the OpenSSL library using the system.security.crytography library in the .net 3.5 world, and I can't seem to get it right. I need some help... part of the issue is my understanding of crytography in general. Here's what is supposed to happen: I send a request for authentication to a device. It returns a challenge digest, which I then need to sign with a known key and return The device returns a "success" or "Fail" message. I have the following code snippet that I am trying to "copy": //Seed the PRNG //Cheating here - the PRNG will be seeded when we create a key pair //The key pair is discarded only doing this to seed the PRNG. DSA *temp_dsa = DSA_new(); if(!temp_dsa) { printf("Error: The client had an error with the DSA API\n"); exit(0); } unsigned char seed[20] = "Our Super Secret Key"; temp_dsa = DSA_generate_parameters(128, seed, sizeof(seed), NULL, NULL, NULL, NULL); DSA_free(temp_dsa); //A pointer to the private key. p = (unsigned char *)&priv_key; //Create and allocate a DSA structure from the private key. DSA *priv_dsa = NULL; priv_dsa = d2i_DSAPrivateKey(NULL, &p, sizeof(priv_key)); if(!priv_dsa) { printf("Error: The client had an error with the DSA API\n"); exit(0); } //Allocate memory for the to be computed signature. sigret = OPENSSL_malloc(DSA_size(priv_dsa)); //Sign the challenge digest recieved from the ISC. retval = DSA_sign(0, pResp->data, pResp->data_length, sigret, &siglen, priv_dsa); A few more bits of information: priv_key is a 252 element character array of hex characters that is included. The end result is a 512 (or less) array of characters to send back for validation to the device. Rasmus asked to see the key array. Here it is: unsigned char priv_key[] = {0x30, 0x81, 0xf9, 0x02, 0x01, 0x00, 0x02, 0x41, 0x00, 0xfe, 0xca, 0x97, 0x55, 0x1f, 0xc0, 0xb7, 0x1f, 0xad, 0xf0, 0x93, 0xec, 0x4b, 0x31, 0x94, 0x78, 0x86, 0x82, 0x1b, 0xab, 0xc4, 0x9e, 0x5c, 0x40, 0xd9, 0x89, 0x7d, 0xde, 0x43, 0x38, 0x06, 0x4f, 0x1b, 0x2b, 0xef, 0x5c, 0xb7, 0xff, 0x21, 0xb1, 0x11, 0xe6, 0x9a, 0x81, 0x9a, 0x2b, 0xef, 0x3a, 0xbb, 0x5c, 0xea, 0x76, 0xae, 0x3a, 0x8b, 0x92, 0xd2, 0x7c, 0xf1, 0x89, 0x8e, 0x4d, 0x3f, 0x0d, 0x02, 0x15, 0x00, 0x88, 0x16, 0x1b, 0xf5, 0xda, 0x43, 0xee, 0x4b, 0x58, 0xbb, 0x93, 0xea, 0x4e, 0x2b, 0xda, 0xb9, 0x17, 0xd1, 0xff, 0x21, 0x02, 0x41, 0x00, 0xf6, 0xbb, 0x45, 0xea, 0xda, 0x72, 0x39, 0x4f, 0xc1, 0xdd, 0x02, 0xb4, 0xf3, 0xaa, 0xe5, 0xe2, 0x76, 0xc7, 0xdc, 0x34, 0xb2, 0x0a, 0xd8, 0x69, 0x63, 0xc3, 0x40, 0x2c, 0x58, 0xea, 0xa6, 0xbd, 0x24, 0x8b, 0x6b, 0xaa, 0x4b, 0x41, 0xfc, 0x5f, 0x21, 0x02, 0x3c, 0x27, 0xa9, 0xc7, 0x7a, 0xc8, 0x59, 0xcd, 0x5b, 0xdd, 0x6c, 0x44, 0x48, 0x86, 0xd1, 0x34, 0x46, 0xb0, 0x89, 0x55, 0x50, 0x87, 0x02, 0x41, 0x00, 0x80, 0x29, 0xc6, 0x4a, 0x08, 0x3e, 0x30, 0x54, 0x71, 0x9b, 0x95, 0x49, 0x55, 0x17, 0x70, 0xc7, 0x96, 0x65, 0xc8, 0xc2, 0xe2, 0x8a, 0xe0, 0x5d, 0x9f, 0xe4, 0xb2, 0x1f, 0x20, 0x83, 0x70, 0xbc, 0x88, 0x36, 0x03, 0x29, 0x59, 0xcd, 0xc7, 0xcd, 0xd9, 0x4a, 0xa8, 0x65, 0x24, 0x6a, 0x77, 0x8a, 0x10, 0x88, 0x0d, 0x2f, 0x15, 0x4b, 0xbe, 0xba, 0x13, 0x23, 0xa1, 0x73, 0xa3, 0x04, 0x37, 0xc9, 0x02, 0x14, 0x06, 0x8e, 0xc1, 0x41, 0x40, 0xf1, 0xf6, 0xe1, 0xfa, 0xfb, 0x64, 0x28, 0x02, 0x15, 0xce, 0x47, 0xaa, 0xce, 0x6e, 0xfe}; Can anyone help me translate this code to it's VB.net crypto equivalent? TIA, Glenn

    Read the article

  • How can I properly implement inetcpl.cpl as an external dll?

    - by Kyt
    I have the following 2 sets of code, both of which produce the same results: using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ResetIE { class Program { [DllImport("InetCpl.cpl", SetLastError=true, CharSet=CharSet.Unicode, EntryPoint="ClearMyTracksByProcessW")] public static extern long ClearMyTracksByProcess(IntPtr hwnd, IntPtr hinst, ref TargetHistory lpszCmdLine, FormWindowState nCmdShow); static void Main(string[] args) { TargetHistory th = TargetHistory.CLEAR_TEMPORARY_INTERNET_FILES; ClearMyTracksByProcessW(Process.GetCurrentProcess().Handle, Marshal.GetHINSTANCE(typeof(Program).Module), ref th, FormWindowState.Maximized); Console.WriteLine("Done."); } } and ... static class NativeMethods { [DllImport("kernel32.dll")] public static extern IntPtr LoadLibrary(string dllToLoad); [DllImport("kernel32.dll")] public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName); [DllImport("kernel32.dll")] public static extern bool FreeLibrary(IntPtr hModule); } public class CallExternalDLL { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate long ClearMyTracksByProcessW(IntPtr hwnd, IntPtr hinst, ref TargetHistory lpszCmdLine, FormWindowState nCmdShow); public static void Clear_IE_Cache() { IntPtr pDll = NativeMethods.LoadLibrary(@"C:\Windows\System32\inetcpl.cpl"); if (pDll == IntPtr.Zero) { Console.WriteLine("An Error has Occurred."); } IntPtr pAddressOfFunctionToCall = NativeMethods.GetProcAddress(pDll, "ClearMyTracksByProcessW"); if (pAddressOfFunctionToCall == IntPtr.Zero) { Console.WriteLine("Function Not Found."); } ClearMyTracksByProcessW cmtbp = (ClearMyTracksByProcessW)Marshal.GetDelegateForFunctionPointer(pAddressOfFunctionToCall, typeof(ClearMyTracksByProcessW)); TargetHistory q = TargetHistory.CLEAR_TEMPORARY_INTERNET_FILES; long result = cmtbp(Process.GetCurrentProcess().Handle, Marshal.GetHINSTANCE(typeof(ClearMyTracksByProcessW).Module), ref q, FormWindowState.Normal); } } both use the following Enum: public enum TargetHistory { CLEAR_ALL = 0xFF, CLEAR_ALL_WITH_ADDONS = 0x10FF, CLEAR_HISTORY = 0x1, CLEAR_COOKIES = 0x2, CLEAR_TEMPORARY_INTERNET_FILES = 0x8, CLEAR_FORM_DATA = 0x10, CLEAR_PASSWORDS = 0x20 } Both methods of doing this compile and run just fine, offering no errors, but both churn endlessly never returning from their work. The PInvoke code was ported from the following VB, which was fairly difficult to track down: Option Explicit Private Enum TargetHistory CLEAR_ALL = &HFF& CLEAR_ALL_WITH_ADDONS = &H10FF& CLEAR_HISTORY = &H1& CLEAR_COOKIES = &H2& CLEAR_TEMPORARY_INTERNET_FILES = &H8& CLEAR_FORM_DATA = &H10& CLEAR_PASSWORDS = &H20& End Enum Private Declare Function ClearMyTracksByProcessW Lib "InetCpl.cpl" _ (ByVal hwnd As OLE_HANDLE, _ ByVal hinst As OLE_HANDLE, _ ByRef lpszCmdLine As Byte, _ ByVal nCmdShow As VbAppWinStyle) As Long Private Sub Command1_Click() Dim b() As Byte Dim o As OptionButton For Each o In Option1 If o.Value Then b = o.Tag ClearMyTracksByProcessW Me.hwnd, App.hInstance, b(0), vbNormalFocus Exit For End If Next End Sub Private Sub Form_Load() Command1.Caption = "??" Option1(0).Caption = "?????????????" Option1(0).Tag = CStr(CLEAR_TEMPORARY_INTERNET_FILES) Option1(1).Caption = "Cookie" Option1(1).Tag = CStr(CLEAR_COOKIES) Option1(2).Caption = "??" Option1(2).Tag = CStr(CLEAR_HISTORY) Option1(3).Caption = "???? ???" Option1(3).Tag = CStr(CLEAR_HISTORY) Option1(4).Caption = "?????" Option1(4).Tag = CStr(CLEAR_PASSWORDS) Option1(5).Caption = "?????" Option1(5).Tag = CStr(CLEAR_ALL) Option1(2).Value = True End Sub The question is simply what am I doing wrong? I need to clear the internet cache, and would prefer to use this method as I know it does what I want it to when it works (rundll32 inetcpl.cpl,ClearMyTracksByProcess 8 works fine). I've tried running both as normal user and admin to no avail. This project is written using C# in VS2012 and compiled against .NET3.5 (must remain at 3.5 due to client restrictions)

    Read the article

< Previous Page | 66 67 68 69 70 71 72 73 74 75 76 77  | Next Page >