lundi 11 mai 2015

Parameter @code1 has no default value

I'm creating this code to use two comboboxes, one that depends on the first, but when I'm trying to select the "code_Zone" from the Table "Zone" I have this exception:

Parameter @code1 has no default value

This is my code:

Dim cmd3 = New OleDbCommand("select [Code_Zone] from [Zone] where [Nom_Zone]= '@code';", connection)
cmd3.Parameters.AddWithValue("@code", ComboBoxNomZoneDeclaration.SelectedText.ToString)
Dim valeur = cmd3.ExecuteScalar
Dim commande = New OleDbCommand("select [Code_Cable] from [CableEnFibre] where [Code_Zone]=@code1;", connection)
commande.Parameters.AddWithValue("@code1", valeur)
Dim reader = commande.ExecuteReader   'there is the exception 
While reader.Read
    ComboBoxPanneCentreAppel.Items.Add(reader.GetInt32(reader.GetOrdinal("Code_Cable")))
End While
reader.Close()

Different Browsers are displaying HTML differently

I am working on some HTML code, its really old code so its not something I am really used to seeing. I made a small change to the code, moved the save button, but when I display it in each of the browsers im testing on, Firefox,Chrome,IE they all look different. Firefox is displaying it the way I want it to enter image description here

But the other two are displaying the same page, with the same exact code incorrectly. IE enter image description here

Chromeenter image description here

Here is my code, please let me know what has gone wrong im not sure how to fix this is issue. Thanks!

    <div id="textdefaults" runat="server">
    <div>
    <asp:Button ID="btnSubmitTextDefaults" Text="Save" runat="server" Height="29px" style="margin-left: 900px" Width="64px" OnClick="btnSubmitTextDefaults_Click" OnClientClick="SaveLanguage();" />
    </div>
    <div class="aTab">
        <asp:UpdatePanel ID="upTextDefaults" runat="server" UpdateMode="Conditional">
            <ContentTemplate>
                <div class="aTab">
                <TagUpdate:TextDefaults id="myTextDefaults" runat="Server" />
                    <asp:UpdateProgress ID="UpdateProgress3" runat="server">
                        <ProgressTemplate>
                            <div class="progress">
                            <asp:Image ID="imgTextDefaults" runat="server" ImageUrl="~/Bannerlink/Images/ajax-loader-big.gif" />Saving...
                            </div>
                        </ProgressTemplate>
                    </asp:UpdateProgress>
                </div>
            </ContentTemplate>
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="btnSubmitTextDefaults" EventName="Click" />
            </Triggers>
        </asp:UpdatePanel>
    </div>
   <br />
</div>

how to process.MainWindowTitle.Contains(str1,str2,str3.....)

I am trying to find more than one MainWindowTitle to a process

for example I have a string in My.resource like this: google:yahoo:msn:ebay....etc and I

have this code to look if one of the strings in my resource string exists to

show a message box

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    Dim LOKUP As New Process
    For Each LOKUP In Process.GetProcesses
        If LOKUP.MainWindowTitle.Contains(Split(My.Resources.String2, ":").ToString) Then
            MsgBox("Allowed - Site - Web")
        Else
            MsgBox("This Site Is Forbidden Sorry")
            'close site
        End If
    Next
End Sub

the problem this code didn't work because the function Contains have only one string.

thank you for your help in advance

Calling COM method results in 'type mismatch' error code -2146828275

I'm calling a COM object from .NET, and the 4th line below is erroring out.

object1 = CreateObject("something1.something2")
object1.OpenDocument(fileNameCopy, False, 0)
object1.SetProperty("Status", "Edit")
object1.CloseDocument()

The error is:

Type mismatch

Error code:

-2146828275

How can I be passing the wrong type to CloseDocument()? Is it something other than a method? If so, how can I determine how to use it if I only have the DLL, and not the source code?

This works on other machines, so it seems to be an environment or version issue.

I searched on SO and found similar questions, but no solution.

Button event handler not fired and the text box value not stored when navigating to another pages

I am just learning ASP.net. Well, I have a little problem with asp.net web page. I have 2 web forms, WebForm1 with just a single DataGrid control, and WebForm2 with a pair of Label and TextBox, and 2 Buttons.

Straight to the point, here is my code for WebForm1:

Imports System.Configuration.ConfigurationManager
Imports System.Data.SqlClient

Public Class WebForm1
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim strConn As String = ConnectionStrings("ConnStr").ConnectionString
        Dim sqlConn As SqlConnection = New SqlConnection(strConn)
        Dim sqlComd As SqlCommand = New SqlCommand
        Dim sqlRead As SqlDataReader = Nothing
        Dim sqlParm As SqlParameter

        sqlParm = New SqlParameter("@Criteria", SqlDbType.NVarChar, 50)
        sqlParm.Value = ""

        sqlComd.Connection = sqlConn
        sqlComd.CommandText = "ShowCategory"
        sqlComd.Parameters.Add(sqlParm)
        sqlComd.CommandType = CommandType.StoredProcedure

        Try
            sqlConn.Open()
            sqlRead = sqlComd.ExecuteReader()
            grdCategory.DataSource = sqlRead
            grdCategory.DataBind()
        Catch ex As Exception
            Throw ex
        Finally
            sqlConn.Close()
        End Try
    End Sub

    Private Sub grdCategory_SelectedIndexChanged(sender As Object, e As EventArgs) Handles grdCategory.SelectedIndexChanged
        Server.Transfer("~/WebForm2.aspx", False)
    End Sub
End Class

And here is my code for WebForm2:

Imports System.Configuration.ConfigurationManager
Imports System.Data.SqlClient

Public Class WebForm2
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim prevPage As Page = Me.Page.PreviousPage
            If prevPage IsNot Nothing Then
                Dim ctn As ContentPlaceHolder = CType(prevPage.Master.FindControl("MainContent"), ContentPlaceHolder)
                Dim grd As GridView = CType(ctn.FindControl("grdCategory"), GridView)
                ViewState("ID") = grd.SelectedRow.Cells(1).Text
                txtName.Text = grd.SelectedRow.Cells(2).Text
                txtDesc.Text = grd.SelectedRow.Cells(3).Text
            End If
        End If
    End Sub

    Protected Sub btnBack_Click(sender As Object, e As EventArgs) Handles btnBack.Click
        Response.Redirect("~/WebForm1.aspx")
    End Sub

    Protected Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
        Dim strConn As String = ConnectionStrings("ConnStr").ConnectionString
        Dim sqlConn As SqlConnection = New SqlConnection(strConn)
        Dim sqlComd As SqlCommand = New SqlCommand
        Dim sqlParm(2) As SqlParameter

        sqlParm(0) = New SqlParameter("@CategoryID", SqlDbType.Int, 0)
        sqlParm(1) = New SqlParameter("@CategoryName", SqlDbType.NVarChar, 15)
        sqlParm(2) = New SqlParameter("@Description", SqlDbType.NText)

        sqlParm(0).Value = ViewState("ID").ToString
        sqlParm(1).Value = txtName.Text.Trim
        sqlParm(2).Value = txtDesc.Text.Trim

        sqlComd.Parameters.AddRange(sqlParm)
        sqlComd.CommandText = "InsertCategory"
        sqlComd.CommandType = CommandType.StoredProcedure

        Try
            sqlConn.Open()
            sqlComd.ExecuteNonQuery()
        Catch ex As Exception
            Throw ex
        Finally
            sqlConn.Close()
        End Try
    End Sub
End Class

The logic is, I select a row in datagrid control and pass the values of the selected row to the textbox control in WebForm2.

But after I change the value of the textbox and I press save button, the btnSave_Click did not executed and it seem the value of the textbox did not change too. I try debugging, and after I press the save button, it execute the page_load event and did not execute the btnSave_Click event.

The questions, is anyone know the reason why the btnSave_Click event did not executed, and how to fix it, so the btnSave_Click can executed after I press the button.

EDIT

Here is the markup for each web form

Webform1

<%@ Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master" CodeBehind="WebForm1.aspx.vb" Inherits="WebApplication2.WebForm1" %>

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
    <asp:GridView ID="grdCategory" runat="server" AutoGenerateSelectButton="True" CellPadding="4" ForeColor="#333333" GridLines="None">
        <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
        <EditRowStyle BackColor="#999999" />
        <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
        <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
        <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
        <SortedAscendingCellStyle BackColor="#E9E7E2" />
        <SortedAscendingHeaderStyle BackColor="#506C8C" />
        <SortedDescendingCellStyle BackColor="#FFFDF8" />
        <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
    </asp:GridView>
</asp:Content>

Webform2

<%@ Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master" CodeBehind="WebForm2.aspx.vb" Inherits="WebApplication2.WebForm2" %>

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
    <br />
    <div class="row">
        <div class="col-md-2">
            <p>Category Name: </p>
        </div>
        <div class="col-md-10">
            <asp:TextBox ID="txtName" Width="300px" runat="server"></asp:TextBox>
        </div>
    </div>
    <div class="row">
        <div class="col-md-2">
            <p>Description: </p>
        </div>
        <div class="col-md-10">
            <asp:TextBox ID="txtDesc" Width="300px" runat="server" TabIndex="1"></asp:TextBox>
        </div>
    </div>
    <div class="row">
        <div class="col-md-2">
        </div>
        <div class="col-md-10">
            <asp:Button ID="btnBack" runat="server" Text="Back" Width="70px" OnClick="btnBack_Click" />
            &nbsp;<asp:Button ID="btnSave" Width="70px" Text="Save" runat="server" OnClick="btnSave_Click" />
        </div>
    </div>
</asp:Content>

WMP Video Only Shows Visualization in VB.NET

I have created a basic form with Windows Media Player embedded into it. I followed the instructions in this article: http://ift.tt/1zW7zNH

The issue I have is that it only shows the visualization for videos, as if it were an audio file. So it plays the audio just fine, but it doesn't show the visual of the video. I have tried MP4, AVI, MOV, and WMV, so I know it's not an issue with the video format I'm using. Everything else works fine too: changing the UIMode, stopping/playing, etc.

The weird thing, too, is that the exact same code will run just fine on other PC's, but not mine. I tried reinstalling WMP, to no avail. I'm thinking it's an issue in my WMP configuration and not in the code then? Not sure. Any help would be greatly appreciated!

Migration from vba to vb.net - correct logic for using Iserror

I'm trying to use this code:

If Not IsError(Convert.ToDateTime(DatiBase(i).innertext.substring(DatiBase(i).innertext.indexof(":") + 1).trim(), New CultureInfo("it-IT"))) Then
    MyString = "'" & Convert.ToDateTime(DatiBase(i).innertext.substring(DatiBase(i).innertext.indexof(":") + 1).trim(), New CultureInfo("it-IT")).ToString("yyyy-MM-dd") & "'"
Else
    'Do something else
End If

My goal is to assign value to "MyString" only if "Convert.ToDateTime" gives a valid value but the code doesn't do that: It stops when the String isn't recognized as a valid DateTime instead of execute the "else" code.

Fill two datagridviews from one tableadapter

Is it possible to fill two datagridviews Datagridview1 & Datagridview2 frome one dataset < one tableadapter < 2 Different queries

From query 1 = DGV1 i need to fill datagridview1
From query 2 - DGV2 i need to fill datagridview2

enter image description here

Create Outlook message with Signture in Visual Basic

With the code below I can open an open message in outlook and add a subject line and some text in the body.

The problem I have it doesn't keep or use the users signature.

Any thoughts on how to keep or use the signature?

        Dim Outlook As Object
        Outlook = CreateObject("Outlook.Application")

        If Outlook IsNot Nothing Then
            Dim omsg As Object
            omsg = Outlook.CreateItem(0)
            omsg.subject = "Your Case Reference is" &
            omsg.body = "Hi" & vbNewLine & vbNewLine & _

            omsg.Display(False) 
        End If

Why does ASP.NET TreeView node expanding only works on page load?

I am populating an ASP.NET (VB) TreeView with data from a database. While populating the tree, I programmatically expand specific nodes based on their data. The node expansion is completed correctly when called for non-postbacks but not for postbacks after a button click. I am thinking that the page lifecycle is resetting the formatting somehow on button postbacks. Does anyone know how I can populate the TreeView nodes with formatting intact for button postbacks?

'Formatting intact
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    loadTreeView("MyTree")
End Sub

'Formatting not intact
    Public Sub btnLoadHierarchy_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnLoadHierarchy.Click
            loadTreeView("MyTree")
    End Sub

How to find device type whether is it a computer or mobile in vb.net with SQL Server

I have a project in that i have to know the device type whether is it a computer or mobile. I am having IP address, I searched everywhere but i have not found the answer so please suggest me if you have any ideas.

Un-Expose Public Control Classes

I have a problem making a custom control. When I create and build the control is in my toolbox which is kind of what I was after:

Public Class PanelBar
    Inherits Panel

    Private _mCusBtn As CustomButton

    Public Sub New()

        InitializeComponent()

        _mCusBtn = New CustomButton()
        AddHandler _mCusBtn.ButtonClicked, AddressOf CustomButtonClicked
        Controls.Add(_mCusBtn)

    Public Sub CustomButtonClicked(ByVal btn As CustomButton, ByVal buttonId As Int32)

        ' Do important stuff here...

    End Sub

End Class

However, when It displays in the toolbox this control also displays:

Public Class CustomButton
    Inherits Button

    Public Property BtnId As Integer
    Public Property BtnColor As Color
    Public Event ButtonClicked(sender As CustomButton, buttonId As Int32)

    Public Sub New()

        ' Set new property values

    End Sub

    Private Sub CustomButtonClicked(sender As Object, e As EventArgs) Handles Me.Click
        RaiseEvent ButtonClicked(Me, BtnId)
    End Sub

End Class

So I have tried setting the CustomButton class to friend to limit the outside access because I do not want this as a control in my toolbox and I get this error: 'btn' cannot expose type 'CustomButton' outside the project through class 'PanelBar'. on the CustomButtonClicked event of the first class.

I'm not sure if this makes sense to want to limit the scope of the controls that help make up my custom control since it is having to access the events on them. To be honest I do not recall one time that I have come across a custom control that doesn't list the controls that make it up, so I am not entirely certain this is going to be possible...but I would really appreciate any advice I can get.

I'm trying to make a simple invoice program working (EDP)

The program is simple, it asks for the first and last name of the user along with three other interactive user input elements. When the user types in the first and last name it should use an array and send the name to a ComboBox via a click of a button. At the moment I don't know how to send the user typed values to the Combox using an array.

Below is the code I have right now:

Public Class Form1

Dim people(20) As String
Dim peopleIndex As Integer
Dim firstName As String
Dim lastName As String
Dim blnGroup As Boolean
Dim numberOfAdult As Integer
Dim numberOfChild As Integer

Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
    peopleIndex = -1



End Sub

Private Sub btnAddCustomer_Click(sender As System.Object, e As System.EventArgs) Handles btnAddCustomer.Click

    peopleIndex += 1
    If peopleIndex > UBound(people) Then
        ReDim Preserve people(peopleIndex + 10)
    End If




End Sub

End Class

how to get bool value from List

hi i am converting a vb project into c# from a youtube tutorial by mkaatr he use a variable

 Private DBMSResultSets As List(Of Object)

so i use a variable in c# private List<object> DBMSResultSets;

and later in code he use a function with return type bool and he use a method

return DBMSResultSets(I).Read

so i use the same thing but visual studio give me error so hover on vb code (DBMSResultSets(I).Read)it say "get or set the element at the specified index"

so i look around and find out that if i write return DBMSResultSets[(int)I]); it do the same thing which is ("get or set the element at the specified index")

now visual studio give me error that can not convert object to bool so i use convert.to and also try the (bool) mean try to typecast but both method didn't work so i need help i am giving you the whole vb code and also my conversion c# code

the problem is in function ReadAndNotEOF

vb code

Imports System.Data.SqlClient

    ' this class will be used to manage connectivity with the database
    Public Class DBMSClass

        ' define the connection string
        Private DBMSConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Asus\Desktop\LibraryManagementSystem\Database\LMS.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=true"

        ' define the connection
        Private DBMSConnectionObj As System.Data.SqlClient.SqlConnection

        ' define the transaction
        Private DBMSTransactionObj As System.Data.SqlClient.SqlTransaction

        ' define the commands object and result sets
        Private DBMSCommands As List(Of System.Data.SqlClient.SqlCommand)
        Private DBMSCommandCodes As List(Of Long)
        Private DBMSResultSets As List(Of Object)

        ' command counter
        Private DBMSCommandCounter As Long

        ' open database connection
        Public Function OpenDB() As String
            Try
                ' open the connection
                DBMSConnectionObj = New SqlConnection(My.Settings.myconnection)
                DBMSConnectionObj.Open()

                ' create the transaction
                DBMSTransactionObj = DBMSConnectionObj.BeginTransaction

                ' prepare the commands list
                DBMSCommands = New List(Of System.Data.SqlClient.SqlCommand)
                DBMSCommandCodes = New List(Of Long)
                DBMSResultSets = New List(Of Object)

                ' prepare the command counter
                DBMSCommandCounter = 0

                ' return ok
                Return "OK"
            Catch ex As Exception
                Return ex.Message
            End Try
        End Function

        ' this is used to run sql commands
        Public Sub ExecuteSQL(ByVal SQL As String, ByVal ParamArray Obj() As Object)

            ' build the command object
            Dim CMD As New System.Data.SqlClient.SqlCommand(SQL, Me.DBMSConnectionObj, Me.DBMSTransactionObj)

            ' add the parameters to the sql command
            Dim I As Integer
            For I = 0 To Obj.Length - 1
                CMD.Parameters.AddWithValue("@" & I, Obj(I))
            Next

            ' run the sql
            CMD.ExecuteNonQuery()

        End Sub

        ' this function is used to commit a transaction
        Public Sub Commit()
            Me.DBMSTransactionObj.Commit()
            Me.DBMSTransactionObj = Me.DBMSConnectionObj.BeginTransaction
        End Sub

        ' this function is used to rollback a transaction
        Public Sub Rollback()
            Me.DBMSTransactionObj.Rollback()
            Me.DBMSTransactionObj = Me.DBMSConnectionObj.BeginTransaction
        End Sub

        ' this function is used to create a result set
        Public Function CreateResultSet(ByVal SQL As String, ByVal ParamArray OBJ() As Object) As Long
            DBMSCommandCounter += 1

            ' build the command object
            Dim CMD As New System.Data.SqlClient.SqlCommand(SQL, Me.DBMSConnectionObj, Me.DBMSTransactionObj)

            ' add the parameters to the sql command
            Dim I As Integer
            For I = 0 To OBJ.Length - 1
                CMD.Parameters.AddWithValue("@" & I, OBJ(I))
            Next

            ' read the data
            Dim RS = CMD.ExecuteReader(CommandBehavior.Default)

            ' store objects in list
            Me.DBMSCommandCodes.Add(DBMSCommandCounter)
            Me.DBMSCommands.Add(CMD)
            Me.DBMSResultSets.Add(RS)

            Return DBMSCommandCounter
        End Function

        ' this function is used to close a result set
        Public Sub CloseResultSet(ByVal Nmbr As Long)
            Dim I As Integer
            For I = 0 To Me.DBMSCommandCodes.Count - 1

                ' find the command and result set
                If DBMSCommandCodes(I) = Nmbr Then

                    ' get the objects
                    Dim R = Me.DBMSResultSets(I)
                    Dim C = Me.DBMSCommands(I)

                    ' remove the objects from the list
                    Me.DBMSResultSets.RemoveAt(I)
                    Me.DBMSCommands.RemoveAt(I)
                    Me.DBMSCommandCodes.RemoveAt(I)

                    ' return the resources
                    R.Close()
                    R.Dispose()
                    C.Dispose()

                    Return

                End If
            Next

            Throw New Exception("the command or result set does not exist")
        End Sub

        ' this function is used to read a single record from db
        Public Function ReadAndNotEOF(ByVal Code As Long) As Boolean
            ' do a search
            Dim I As Long
            For I = 0 To Me.DBMSCommandCodes.Count - 1
                If DBMSCommandCodes(I) = Code Then
                    Return DBMSResultSets(I).Read
                End If
            Next
            Throw New Exception("Command or Resultset does not exist")
        End Function

        ' this function is used to get a column value from db
        Public Function GetColumnValue(ByVal Code As Long, ByVal ColumnName As String) As Object
            Dim I As Long
            For I = 0 To Me.DBMSCommands.Count - 1
                If DBMSCommandCodes(I) = Code Then
                    Return DBMSResultSets(I).Item(ColumnName)
                End If
            Next
            Throw New Exception("Command or Resultset does not exist")
        End Function
    End Class

my c# code

//this class will be used to manage connectivity with the database
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Sql;
using System.Data;
using System.Data.SqlClient;

namespace Library_main
{
    public class DBMSClass
    {
        //define the connection string

        // private String DBMSConnectionString = "Data Source=(LocalDB)\\v11.0;AttachDbFilename="\\D:\\tutorial\\c # tutorial\\3 may 2015\\Library_main\\Library_main\\bin\\Debug\\DataBase\\LMS.mdf";"Integrated Security=True;Connect Timeout=30";
        //define the connection
        private SqlConnection DBMSConnectionObj = null;
        //define the transaction
        private SqlTransaction DBMSTransactionObj;

        // define the commands object and result sets
        private List<SqlCommand> DBMSCommands;
        private List<long> DBMSCommandCodes;
        private List<object> DBMSResultSets;
        // command counter
        private long DBMSCommandCounter;

        //open database connection
        public string OpenDB()
        {
            try
            {
                //open the connection
                DBMSConnectionObj = new SqlConnection(Properties.Settings.Default.ConnectionString);
                DBMSConnectionObj.Open();
                //creat the transaction
                DBMSTransactionObj = DBMSConnectionObj.BeginTransaction();
                //prepare the commands list
                DBMSCommands = new List<SqlCommand>();
                DBMSCommandCodes = new List<long>();
                DBMSResultSets = new List<object>();
                // prepare the command counter
                DBMSCommandCounter = 0;
                //return ok
                return "ok";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        //this is used to run sql commands
        public void ExceuteSQL(string SQL, params object[] Obj)
        {
            //build the command object
            SqlCommand CMD = new SqlCommand(SQL, this.DBMSConnectionObj, this.DBMSTransactionObj);

            //add the parameters to the sql command
            int I;
            int count = Obj.Length - 1;
            for (I = 0; I <= count; I++)
            {
                CMD.Parameters.AddWithValue("@" + I, Obj[I]);
            }
            //run the sql
            CMD.ExecuteNonQuery();
        }

        //this funtion to commit 
        public void Commit()
        {
            this.DBMSTransactionObj.Commit();
            this.DBMSTransactionObj = this.DBMSConnectionObj.BeginTransaction();
        }

        // this function is used to rollback a transaction
        public void Rollback()
        {
            this.DBMSTransactionObj.Rollback();
            this.DBMSTransactionObj = this.DBMSConnectionObj.BeginTransaction();
        }

        //this function is used to creat a result set
        public long CreatResultSet(string SQL, params object[] Obj)
        {
            DBMSCommandCounter += 1;
            // build the command object
            SqlCommand CMD = new SqlCommand(SQL, this.DBMSConnectionObj, this.DBMSTransactionObj);

            // add the parameters to the sql command
            int I = 0;
            for (I = 0; I <= Obj.Length - 1; I++)
            {
                CMD.Parameters.AddWithValue("@" + I, Obj[I]);
            }
                // read the data
                dynamic RS = CMD.ExecuteReader(System.Data.CommandBehavior.Default);

                // store objects in list
                this.DBMSCommandCodes.Add(DBMSCommandCounter);
                this.DBMSCommands.Add(CMD);
                this.DBMSResultSets.Add(RS);
            return DBMSCommandCounter;
        }

        // this function is used to close a result set
        public void CloseResultSet(long Nmbr)
        {
            int I = 0;

            for (I = 0; I <= this.DBMSCommandCodes.Count - 1; I++)
            {
                // find the command and result set

                if (DBMSCommandCodes[I] == Nmbr)
                {
                    // get the objects
                    dynamic R = this.DBMSResultSets[I];
                    dynamic C = this.DBMSCommands[I];

                    // remove the objects from the list
                    this.DBMSResultSets.RemoveAt(I);
                    this.DBMSCommands.RemoveAt(I);
                    this.DBMSCommandCodes.RemoveAt(I);

                    // return the resources
                    R.Close();
                    R.Dispose();
                    C.Dispose();
                    return;
                }
            }
            throw new Exception("the command or result set does not exist");
        }

        // this function is used to read a single record from db
        public bool ReadAndNotEOF(long Code)
        {
            // do a search
            long I = 0;
            for (I = 0; I <= this.DBMSCommandCodes.Count - 1; I++)
            {
                if (DBMSCommandCodes[(int)I] == Code)
                {
                    return Convert.ToBoolean(DBMSResultSets[(int)I]);
                }
            }
            throw new Exception("Command or Resultset does not exist");
        }

        // this function is used to get a column value from db
        public object GetColumnValue(long Code, string ColumnName)
        {
            long I = 0;
            for (I = 0; I <= this.DBMSCommandCodes.Count - 1; I++)

                if (DBMSCommandCodes[(int)I] == Code)
                {
                    return DBMSResultSets[(int)I].Equals(ColumnName);
                }

            throw new Exception("Command or Resultset does not exist");
        }

    }
}

Determine who has read a mail in shared mailbox

I'm thinking about a possibility to determine who has read a mail in a shared mailbox at Outlook 2010.

Of course a MailItem don't hold a property like "readBy", that's why I'm looking for a way to respond to the fact that a message has been marked as read. Then i could write the curent user name to a userdefined Field.

My first idea:

Listen to MailItem.Read() or MailItem.Open() with a VBA macro, but - when I'm not wrong - MailItem.Open() is thrown when a MailItem is focused and shown in the reading pane. If Outlook don't mark it as read automatically, the Info "Read by Max" would be wrong. MailItem.Read() is thrown only when a MailItem is opened to a new window, but what's when i press Ctrl+Enter?

After some Googling it seems that VBA isn't able to solve this on a good way or is it? Should I think about writing an Add-In?

Do you have a idea how i could go about this?
Any thoughts would be greatly appreciated


Best regards

Is it possible to associate a concrete value with a field at compile-time?

I'm not sure how to phrase this exactly. I have a class, called BoundedString, which basically looks like:

Public Class BoundedString

    Public Property Value() As String
    Public Property MinLength() As Integer
    Public Property MaxLength() As Integer

End Class

Elsewhere in my code, I want to be able to say:

Public Class SomeClass
    Public Property StringField() As BoundedString(Of 3, 5)
End Class

Where 3 and 5 represent the values of MinLength and MaxLength.

This way, I can statically specify info about my string. The closest thing I've found to this seems to be generics or maybe attributes, but I don't think generics let you specify concrete values. Is anyone aware of a language feature for doing this?

Defibrillator - Display message after timeout

I'm using Defibrillator to Keep my ASP .NET Session Alive for 5 minutes, even the user is not doing anything for 5 minutes. After 5 minutes of inactivity, I'm looking display a message/popup to the user as "you session is timed out and you're record is released and so on..". Aspx Code for Defibrillator:

Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Response.AddHeader("Refresh", Convert.ToString((Session.Timeout*60)-10))    
    End Sub

Added this line of code into the front end WebForm markup language:

<iframe id="Defib" src="../Defibrillator.aspx" frameborder="0" width="0" height="0" runat="server" />

What is the best possible way to do that display the message?? Thanks in Advance

Create a stored setting using buttons (Visual Studio 2013)

so, I have a question, for example, I have created a setting called "example" and it's value is "test". I want my label's text to be the examples text using Label1.Text = My.Settings.example(). But I would like to know how to create a new setting using a button, so when I click the button, it will create a new setting called "example2" and it's value "test2", and I would also like to know how to DELETE an setting using a button, thankyou, sorry for my english.

PushStreamContent using SqlDataReader.ExecuteReaderAsync to stream CSV or delimited file to client

I'm trying to utilize WebAPI to stream a large amount of data from SQL Server to a delimited file without waiting for the entire result set to return from the database. I'm really terrible with Async and Await, haven't wrapped my head around it. It seems what I'd like to do should be possible using the PushStreamContent and the SqlDataReader async methods.
This is at my DataAccessLayer:

   Public Async Function ExecuteToResponseStream(command As SqlCommand, responseStream As IO.Stream) As Threading.Tasks.Task
      Using responseStream
         Dim newConString As String = _conString
         Using con As SqlConnection = New SqlConnection(newConString)
            Await con.OpenAsync()
            'Add params
            command.Connection = con

            Using ms As IO.MemoryStream = New IO.MemoryStream
               Using ts As IO.StreamWriter = New IO.StreamWriter(ms)

                  Using reader As SqlDataReader = Await command.ExecuteReaderAsync(CommandBehavior.SequentialAccess)
                     While Await reader.ReadAsync()
                        Dim loValues As New List(Of String)
                        For i = 0 To reader.FieldCount - 1
                           loValues.Add(reader(i).ToString)
                        Next
                        Await ts.WriteAsync(String.Join(vbTab, loValues.ToArray))
                        Await ms.CopyToAsync(responseStream)
                     End While
                  End Using
               End Using
            End Using
         End Using
      End Using
   End Function

My repository has a method with signature of: Function ExportAsync(id As String, responseStream As IO.Stream) As Task

Finally, the WebAPI Client:

   Public Function Export(id As String) As HttpResponseMessage
      Dim resp As New HttpResponseMessage(HttpStatusCode.OK)
      Dim onStreamAvailable As Action(Of IO.Stream, HttpContent, TransportContext) = Async Sub(responseStream, content, context)
        Await repository.ExportAsync(rc, responseStream)
     End Sub

      resp.Content = New PushStreamContent(onStreamAvailable)
      resp.Content.Headers.ContentType = New Headers.MediaTypeHeaderValue("application/octet-stream")
      resp.Content.Headers.ContentDisposition = New Headers.ContentDispositionHeaderValue("attachment")
      resp.Content.Headers.ContentDisposition.FileName = "Somefilename"

      Return resp
   End Function

The client function seems to exit appropriately and return the response, eventually. The eventual response to the browser does indeed look like an attachment, it's empty, I suck at streams, but it seems like it not happening in that magical asynchronous way.

Also, it seems to me that this would be a somewhat simple exercise though I can't find a good implementation out there on the webs. Perhaps I'm going about this completely wrong.

Page redirection not hitting break points in Visual Studio

I have a survey application which user fills the info and then clicks Submit and gets redirected to other page(Success.aspx) which simply shows a message "Survey was saved!"

After that I want to redirect user automatically to the login page. I found the following code:

<meta http-equiv="refresh" content="3;url=Login.aspx/" />

Above code "Does" work. User gets redirected to login.aspx after 3 seconds, however code does not break in Visual Studio(2013) anymore. If user tries to login, code directs him to the survey page Response.Redirect("Survey.aspx")

but the break point that I put in the load even of that page will no longer works.

If I remove

 <meta http-equiv="refresh" content="3;url=Login.aspx/" />

Breakpoints work again! Is this a known issue?

Add Range from one list to another

I have a list(of string) and I search it to get a start and end range, I then need to add that range to a separate list

ex: List A = "a" "ab" "abc" "ba" "bac" "bdb" "cba" "zba"

I need List B to be all the b's (3-5)

What I want to do is ListB.Addrange(ListA(3-5))
How can I accomplish this??

How to set different freeze panes for different sheets in a excel using vb.net

I want to set different freeze panes for different sheets in a excel. I tried using the below code but this is being assigned to all sheets. But I want to freeze first 6 rows in my first sheet and only top row in second sheet. I tried so many ways but no result. Any suggestions? Thanks in advance

With xlApp.ActiveWindow
                .SplitColumn = 0
                .SplitRow = 6
            End With

VB call subroutine on button click

I have following subroutine written in vb:

Public Sub Command1_Click()
    Dim idm1 As CIDMLinkTransmitter
    Dim referer As String
    Dim cookie As String
    Dim postData As String
    Dim user As String
    Dim password As String
    idm1 = CreateObject("IDMan.CIDMLinkTransmitter")
    idm1.SendLinkToIDM("http://ift.tt/1QBOXGI",
    referrer, cookie, postData, user, password, "C:\", "idman401.exe", 0)
End Sub

I am trying to call this subroutine on a button click. I use Call statement but it gave me syntax error.

Call Command1_Click() //Syntax Error

I just want to test if subroutine works. How can I do that?

The underlying connection was closed: An unexpected error occurred on a send in SOAP webservice

I have a reference to a webservice which uses SOAP to process the searches and starting today morning i am receiving the following error:

The underlying connection was closed: An unexpected error occurred on a send.

This will not happen for few requests if the application is restarted and will start receiving these errors after a some time say like 5 minutes and if we restart as said the services are re-processed without any issues.

I have read: http://ift.tt/1cw7Tbs

but those methods will not work for my case. Anyone else have faced similar problem???

Chaining overloaded constructors

I am trying to create an efficient class with minimum code-duplication.

I have this defined:

Public Class Foo
    Private _firstName as string = ""
    Private _lastName as string = ""

    Public Sub New(ByVal userGUID As Guid)
        'query DB to get firstName and lastName
        Me.New(dt.Rows(0)("FirstName").ToString(),dt.Rows(0)("LastName").ToString())
    End Sub

    Public Sub New(ByVal firstName As String, ByVal lastName As String)
        _firstName = firstName.toUpper()
        _lastName = lastName.toUpper()
        Validate()
    End Sub

    Private Sub Validate()
        ' Throw error if something is wrong
    End Sub
End Class

The Constructor with firstName and lastName parameters is the end-point constructor that does validation. A constructor with userGUID as a parameter would query DB to obtain name and call the final constructor. This way all execution should be directed towards one of the constructors that actually does all validation etc etc. The idea behind it is that if I add new contructors, I only have to pull necessary data (firstname/lastname) and call the final constructor that does validation.

However, there is a compilation error preventing me from using this system on line Me.New(dt.Rows(0)("FirstName").ToString(),dt.Rows(0)("LastName").ToString()). Apparently this line has to be the first line in the constructor. But If I have this as first line, it will break the validation process because validation will throw an error due to no firstname/lastname. I have to query the DB in order to pull that info.

I am aware that I can assign values here and call validation from this constructor too, but this will effectively isolate this constructor from the final one, thus duplicating code and adding to maintenance a bit. FYI, in the example below I only have 2 constructors, but in reality i have several more. If each will do its own assignment it just adds up to maintenance that much.

So, is there a way to achieve my task by executing some code and THEN calling an overloaded constructor?

Thank you for any insight

Webresponse returns string "pageRedirect" "ReturnUrl"

I just started learning about HttpWebRequest and HttpWebResponse so please go easy on me.

My issue is that when I try to do a HttpWebRequest POST method to run a search on a work website. The HttpWebResponse I get back is placed in a Richtextbox and look similar to this.

   1|#||4|77|pageRedirect||%2findex.aspx%3fReturnUrl%3d%252fPro%252fRep%252fQue.aspx|

' I can not show the actually code since it is work related information.

I am not sure what this is exactly, but I am think the part the says "pageRedirect" is a good indication.

I have tried HttpWebRequest.AllowAutoRedirect = True but that does not work.

If someone could explain what the string above is I will try to take it from there.

**And I do not know if it might be the problem but this is the second POST Method I am using in the code. I did not find anything that said I could not use two or more POST methods.

**I have been using Live HTTP Header tool to capture the information.

VB.NET - How to use an OFT or a DOCX as a template when sending an email (Exchange Web Service)

I would like to send emails using ExchangeWeb Service by using either an OFT (Outlook Template) or word document as a template.

Here's how I send emails as of now (working):

    Public Sub SendEmailFrom3611(ByVal body As String, _
                                ByVal recipient As List(Of String), _
                                ByVal subject As String)

    Dim exch As ExchangeService = New ExchangeService(ExchangeVersion.Exchange2013)
    Const email3611 As String = "3611@domain.com"
    Const serviceNowUsr As String = "username"
    Const serviceNowPsw As String = "password"

    exch.AutodiscoverUrl(email3611)
    exch.Credentials = New WebCredentials(serviceNowUsr, serviceNowPsw)

    Dim email As New EmailMessage(exch)

    email.From = email3611
    email.ToRecipients.Add(email3611)

    For Each s As String In recipient
        email.ToRecipients.Add(s)
    Next s

    email.Subject = subject
    email.Body = body
    email.Body.BodyType = BodyType.HTML

    email.SendAndSaveCopy()

End Sub

Is it possible to use a word document as a template when sending emails? Before sending the email, I would look in the word document and replace some variables (like %FULLNAME%) with the actual name of the user.

Thanks, Gabriel

Get Bytes by number of lines in Excel file

Dim FileMemCnt As Integer = File.ReadAllBytes(filePath).Length

Hi all,

I'm trying to figure out a way of determining the bytesize of say 1000 rows in a CSV file which may have say 10-20K rows. Once I get the bytesize chunk, I can then split the file into smaller files per exactly 1000 rows. Does anyone know a method that can enable me to therefore get the exact bytesize chunk I need?

Above I have posted a small snippet of code I use that can read the full size of bytes per file, so is there any way similar to read number of bytes per 1000 records?

Visual Studio 2013 ---- Add button to populate a gridview?

Hey I have a question for any skilled coder's out there? I am having trouble finding an answer to my Visual Studio question. I have a form with fields linked to an "Add New Source" button. I want the data in these field to populate the grid view. Could anyone give me advice? Is so I would be grateful and could you explain what you have done as will have to do it again. Also I am writing in VB. Here is the name of my button and Event name.

   Protected Sub btnAddNewSource_Click(sender As Object, e As EventArgs)

    End Sub

Here is my Button

       <dx:LayoutItem ShowCaption="False" ColSpan="1" Width="10%">
                                <LayoutItemNestedControlCollection>
                                    <dx:LayoutItemNestedControlContainer runat="server">
                                        <dx:ASPxButton ID="btnAddNewSource" runat="server" Text="Add New Source" OnClick="btnAddNewSource_Click" Theme="Office2010Blue">
                                        </dx:ASPxButton>
                                    </dx:LayoutItemNestedControlContainer>
                                </LayoutItemNestedControlCollection>
                            </dx:LayoutItem>

Here is my grid view

      <dx:LayoutItem ColSpan="5" RowSpan="2" ShowCaption="False" Width="100%" HorizontalAlign="Center">
                        <LayoutItemNestedControlCollection>
                            <dx:LayoutItemNestedControlContainer runat="server">
                                <dx:ASPxGridView ID="gridContacts" runat="server" AutoGenerateColumns="False" DataSourceID="CostAndFunding" Theme="Office2010Blue" KeyFieldName="GrantApplicationCycleFundingID" Styles-AlternatingRow-BackColor="Wheat">
                                    <Columns>
                                        <dx:GridViewCommandColumn ShowEditButton="True" ShowInCustomizationForm="True" VisibleIndex="0">
                                        </dx:GridViewCommandColumn>
                                        <dx:GridViewDataTextColumn FieldName="GrantApplicationCycleFundingID" ReadOnly="True" ShowInCustomizationForm="True" Visible="False" VisibleIndex="1">
                                            <EditFormSettings Visible="False" />
                                        </dx:GridViewDataTextColumn>
                                        <dx:GridViewDataTextColumn FieldName="GrantApplicationID" ShowInCustomizationForm="True" Visible="False" VisibleIndex="2">
                                        </dx:GridViewDataTextColumn>
                                        <dx:GridViewDataTextColumn FieldName="GrantApplicationCycleFundingSource" ShowInCustomizationForm="True" VisibleIndex="3">
                                        </dx:GridViewDataTextColumn>
                                        <dx:GridViewDataTextColumn FieldName="GrantApplicationCycleFundingContribution" ShowInCustomizationForm="True" VisibleIndex="4">
                                        </dx:GridViewDataTextColumn>
                                        <dx:GridViewDataTextColumn FieldName="GrantApplicationCycleFundingStatusID" ShowInCustomizationForm="True" Visible="False" VisibleIndex="5">
                                        </dx:GridViewDataTextColumn>
                                        <dx:GridViewDataComboBoxColumn Caption="Funding Status" FieldName="FundingStatusDescription" ShowInCustomizationForm="True" VisibleIndex="6" Width="">
                                            <PropertiesComboBox DataSourceID="Select_FundingStatus" IncrementalFilteringMode="Contains" TextField="FundingStatusDescription" ValueField="FundingStatusID" ValueType="System.Int32">
                                            </PropertiesComboBox>
                                        </dx:GridViewDataComboBoxColumn>
                                        <dx:GridViewDataTextColumn FieldName="GrantApplicationCycleFundingNotes" ShowInCustomizationForm="True" VisibleIndex="7">
                                        </dx:GridViewDataTextColumn>
                                    </Columns>
                                    <Settings ShowFilterRow="True" ShowGroupPanel="true" />
                                    <Styles>
                                        <AlternatingRow BackColor="Wheat">
                                        </AlternatingRow>
                                    </Styles>
                                </dx:ASPxGridView>
                            </dx:LayoutItemNestedControlContainer>
                        </LayoutItemNestedControlCollection>
                    </dx:LayoutItem>

Sorry for big question but I am stuck big time. Thanks in advance for anyone attempting to answer this!

Do function right after a proccess ends

Clicks on button

  1. Sbagen process (An open source software) runs at background.
  2. Label2.Text = "Running"
  3. Sbagen process ends automatically after the job done.
  4. Now this is the place I want to edit. I want my software change Label2.Text to "Finished" right after "Sbagen" process ends. How can I achieve this? Tried endless things.

SOLUTION:

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
  ...
        AddHandler timer_watcher.Tick, AddressOf TimerEvent
        timer_watcher.Interval = TimeSpan.FromSeconds(1).TotalMilliseconds
        timer_watcher.Start()
    End If
End Sub

Public Sub TimerEvent(sender As Object, e As EventArgs)
    Dim p() As Process = System.Diagnostics.Process.GetProcessesByName("sbagen")
    If p.Length = 0 Then
        timer_watcher.Stop()
        Label2.Text = "Çevrildi!"
    End If
End Sub

Is there a faster way to draw dynamic rectangles in VB?

I'm designing a program that will have some of the same features as MS Paint in VB.NET. The following code allows me to successfully click-and-drag to draw a selection rectangle on a picturebox, but it seems laggy (especially compared to MS Paint itself). Is there a more efficient way of doing this?

Public DrawCapture As Boolean = False
Public DrawCaptureOrigin As Point
Public DrawCaptureRectangle As Rectangle

Private Sub PictureBox1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseDown
    DrawCapture = True
    DrawCaptureOrigin = e.Location
    DrawCaptureRectangle = New Rectangle(e.Location, New Point(1, 1))
End Sub

Private Sub PictureBox1_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseMove
    Dim curX As Integer = e.Location.X, curY As Integer = e.Location.Y
    Dim dcoX As Integer = DrawCaptureOrigin.X, dcoY As Integer = DrawCaptureOrigin.Y
    If DrawCapture Then
        If curX < dcoX And curY < dcoY Then
            DrawCaptureRectangle = New Rectangle(curX, curY, dcoX - curX, dcoY - curY)
        ElseIf curX < dcoX Then
            DrawCaptureRectangle = New Rectangle(curX, dcoY, dcoX - curX, curY - dcoY)
        ElseIf curY < dcoY Then
            DrawCaptureRectangle = New Rectangle(dcoX, curY, curX - dcoX, dcoY - curY)
        Else
            DrawCaptureRectangle = New Rectangle(dcoX, dcoY, curX - dcoX, curY - dcoY)
        End If
        PictureBox1.Invalidate()
    End If
End Sub

Private Sub PictureBox1_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PictureBox1.MouseUp
    DrawCapture = False
    PictureBox1.Invalidate()
End Sub

Private Sub PictureBox1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles PictureBox1.Paint
    If DrawCaptureRectangle.Width > 0 Then
        e.Graphics.DrawRectangle(Pens.Black, DrawCaptureRectangle)
    End If
End Sub

Checkbox column flickering when scrolling

I want to make a simple table, whit a checkbox column. I created the table as DataGrid and bound it to a List of custom objects.

Everything works fine, except I notice strange flickering effect, when I scroll the table.
It looks like this: http://ift.tt/1J5ufg3

What's the problem? How can I get rid of this?

My xaml code:

<Window x:Class="MainWindow"
xmlns="http://ift.tt/o66D3f"
xmlns:x="http://ift.tt/mPTqtT"
Title="MainWindow" Height="350" Width="723.251">

<Grid>
    <DataGrid x:Name="MainDataGrid" Margin="22,21,133,58" 
              AutoGenerateColumns="False"
              SelectionMode="Single"
              SelectionUnit="Cell"
              CanUserSortColumns="False"
              IsReadOnly="True"
              >
    </DataGrid>
    <Button Content="Populate" HorizontalAlignment="Left" Margin="592,21,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click" IsDefault="True"/>
    <Label x:Name="Lbl1" Content="Label" HorizontalAlignment="Left" Margin="592,48,0,0" VerticalAlignment="Top"/>
</Grid>
</Window>

And vb code:

Imports CADnet_FileReader.CADnet_FileReader

Class MainWindow

Dim OutList As New List(Of Tags)
Dim SelectionLock As New Boolean

Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
    Dim TableColumn_01 As New DataGridTextColumn
    TableColumn_01.Binding = New Binding("TagItem")
    TableColumn_01.Header = "Tag Name"
    TableColumn_01.Width = 200
    Me.MainDataGrid.Columns.Add(TableColumn_01)

    Dim TableColumn_02 As New DataGridCheckBoxColumn

    TableColumn_02.Binding = New Binding("TagCheck")
    TableColumn_02.Header = "Toogle"
    TableColumn_02.Width = 30

    Me.MainDataGrid.Columns.Add(TableColumn_02)

    Dim TempList As New List(Of String)
    Dim path As String = "C:\Epic\Apps\ElementCounter\Epic_Template.txt"
    TempList = ReadTemplateFile(path)

    Dim ThisItem As New Tags

    For i = 0 To TempList.Count - 1
        ThisItem = New Tags
        ThisItem.TagItem = TempList.Item(i)
        ThisItem.TagCheck = False
        OutList.Add(ThisItem)
    Next

    MainDataGrid.ItemsSource = OutList
End Sub

Private Sub MainDataGrid_SelectionChanged(sender As Object, e As SelectionChangedEventArgs) Handles MainDataGrid.SelectionChanged
End Sub

Private Sub MainDataGrid_SelectedCellsChanged(sender As Object, e As SelectedCellsChangedEventArgs) Handles MainDataGrid.SelectedCellsChanged
    Dim SelectedRow As Integer
    Dim SelectedColumn As Integer

    SelectedRow = MainDataGrid.Items.IndexOf(MainDataGrid.CurrentItem)
    SelectedColumn = MainDataGrid.SelectedCells.Item(0).Column.DisplayIndex

    Lbl1.Content = "Selected Row = " & SelectedRow & "; " & SelectedColumn

    If SelectedColumn = 1 Then
        If OutList.Item(SelectedRow).TagCheck = False Then
            OutList.Item(SelectedRow).TagCheck = True
        Else
            OutList.Item(SelectedRow).TagCheck = False
        End If


    End If

End Sub
End Class

List item I used:

<System.Serializable()> Public Class Tags
    Implements INotifyPropertyChanged
    Public Property TagItem As String
    ' New Property
    Private _NewDataProperty As String
    Public Property TagCheck
        Set(value)
            _NewDataProperty = value
            _PropertyChanged("TagCheck")
        End Set
        Get
            Return _NewDataProperty
        End Get
    End Property
    ' Change events
    Private Sub _PropertyChanged(Optional ByVal PropertyName As String = Nothing)
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(PropertyName))
    End Sub
    Private Event PropertyChanged(sender As Object, e As PropertyChangedEventArgs) Implements INotifyPropertyChanged.PropertyChanged

    Public Sub SerializeMe()
    End Sub
End Class

ProcessCmdKey how change focus before send text

I have a form just with a textbox and a datagridview. I would like when user pressed an arrow (up/down) it browses through datagridview and when user pressed any other key it sends to textbox.

It's not working, when datagridview has focus and user press a letter key, it changes focus to textbox, but no text is sent.

My code:

Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message, ByVal keyData As System.Windows.Forms.Keys) As Boolean
If keyData = Keys.Down Or keyData = Keys.Up Then
  grid.Focus()
  Return MyBase.ProcessCmdKey(msg, keyData)
ElseIf Not Me.ActiveControl.Equals(txtFiltro) Then
  Me.ActiveControl = txtFiltro
  txtFiltro.Focus()
  txtFiltro.Select()
  Return MyBase.ProcessCmdKey(msg, keyData)
End If
Return MyBase.ProcessCmdKey(msg, keyData)
End Function

The key is sent before change focus... :(

LibTiff.net doesn't expose Tiff2Pdf?

I'm trying to move away from using a command line app to convert TIFF to PDF; in doing so, I've installed LibTiff.net and tried to convert a file using their provided example.

Even using the sample exactly as they put it, it seems like I can't find the Tiff2Pdf function. I've tried Tiff2Pdf, BitMiracle.Tiff2Pdf, BitMiracle.LibTiff.Classic.Tiff2Pdf, etc.

Imports System
Imports System.Diagnostics
Imports System.Drawing
Imports System.IO
Imports BitMiracle

Namespace BitMiracle.LibTiff.Samples
    Public NotInheritable Class ConvertTiffToPdf
        Public Shared Sub Main()
            Dim inputFile As String = "Sample Data\multipage.tif"
            Dim outputFile As String = "output.pdf"

            Dim arguments As String() = New String() {"-o", outputFile, "-p", "A4", inputFile}
            Tiff2Pdf.Program.Main(arguments)

            Process.Start(outputFile)
        End Sub
    End Class
End Namespace

Is there another reason why this wouldn't be working?

RESTful API call in SSIS package

As part of a SSIS (2005) package I am calling a RESTful API through a script component (VB.NET). I am getting the records back OK. The problem I have though is processing the format it comes back in so I can output it (split into the separate output columns) within the data flow and write into a SQL table. Don't know where to start - anyone got any ideas? I have no control over the API so am stuck with this format.

Here is the schema as per the API documentation:

{StatusMessage : <string>, Unit : <string> [ { VehicleID : <int>, RegistrationNumber : <string>, Description : <string>, VehicleIcon : <string>, LocationText : <string>, Latitude : <double>, Longitude : <double>, Heading : <int>, Speed : <int>, LastEventDateTime : <yyyy-mm-ddThh:mm:ss>, VehicleInitials : <string>, LastEventDescription : <string>, IgnitionState : <int>} ] }

And here is a sample of the data returned (it comes back as a single line of text):

{"Vehicles":[{"VehicleId":512862,"RegistrationNumber":"BJ11 XXX","Description":"Mercedes Sprinter","VehicleIcon":"Vehicle10.png","LocationText":"Sample Address","Latitude":1,"Longitude":-1,"Heading":0,"Speed":0,"LastEventDateTime":"2015-05-11T09:43:39","VehicleInitials":"","LastEventDescription":"Stationary with Ignition OFF at Sample Address Since 09:43","IgnitionState":0,"OdometerReading":0,"OdometerReadingUnit":"imperial","OdometerReadingDate":"0001-01-01","OdometerReadingEnteredBy":"Unknown","ServiceRenewalDate":"0001-01-01","ServiceRenewalOdometerReading":0,"InsuranceRenewalDate":"0001-01-01","RoadTaxRenewalDate":"0001-01-01","MotRenewalDate":"0001-01-01","UserDefinedValue1Name":"","UserDefinedValue1Date":"0001-01-01","UserDefinedValue2Name":"","UserDefinedValue2OdometerReading":0,"DriverIdEnabled":false},{"VehicleId":508992,"RegistrationNumber":"BJ12 ZZZ","Description":"T27","VehicleIcon":"Vehicle11.png","LocationText":"Sample Address 2","Latitude":1,"Longitude":-1,"Heading":0,"Speed":0,"LastEventDateTime":"2015-05-07T15:32:51","VehicleInitials":"T27","LastEventDescription":"Stationary with Ignition OFF at Sample Address Since 07/05/2015 15:32","IgnitionState":0,"OdometerReading":0,"OdometerReadingUnit":"imperial","OdometerReadingDate":"0001-01-01","OdometerReadingEnteredBy":"Unknown","ServiceRenewalDate":"0001-01-01","ServiceRenewalOdometerReading":0,"InsuranceRenewalDate":"0001-01-01","RoadTaxRenewalDate":"0001-01-01","MotRenewalDate":"0001-01-01","UserDefinedValue1Name":" ","UserDefinedValue1Date":"0001-01-01","UserDefinedValue2Name":" ","UserDefinedValue2OdometerReading":0,"DriverIdEnabled":false},{"VehicleId":509203,"RegistrationNumber":"BJ11 CCC","Description":"T02","VehicleIcon":"Vehicle11.png","LocationText":"Sample Address","Latitude":1,"Longitude":-1,"Heading":0,"Speed":0,"LastEventDateTime":"2015-05-11T13:30:22","VehicleInitials":"T02","LastEventDescription":"Stationary with Ignition OFF at Sample Address Since 13:30","IgnitionState":0,"OdometerReading":0,"OdometerReadingUnit":"imperial","OdometerReadingDate":"0001-01-01","OdometerReadingEnteredBy":"Unknown","ServiceRenewalDate":"0001-01-01","ServiceRenewalOdometerReading":0,"InsuranceRenewalDate":"0001-01-01","RoadTaxRenewalDate":"0001-01-01","MotRenewalDate":"0001-01-01","UserDefinedValue1Name":"","UserDefinedValue1Date":"0001-01-01","UserDefinedValue2Name":"","UserDefinedValue2OdometerReading":0,"DriverIdEnabled":false}],"StatusMessage":null,"Unit":"imperial","HttpStatus":200}

Can not found Row 0 in vb.NET

I try to select the first row and first item from my SQL But, it show me message "Can not found Row 0 "

sqlCmd1 = "SELECT Type.Name FROM Type INNER JOIN Room ON Type.TID = Room.TypeID WHERE (((Room.ROID)= " + (roomCB.SelectedIndex + 1).ToString() + "));"
ad = New OleDb.OleDbDataAdapter(sqlCmd1, cnn)
ds = New DataSet
ad.Fill(ds)
Try
    typeTxt.Text = ds.Tables(0).Rows(0).Item(0)
Catch ex As Exception
    MsgBox(ex.Message)
End Try

VB .NET comparing strings

I don't get what's going on. The method equals doesn't work, and neither comparing the strings with the '=' operator or with 'string.compare'. thetruth is always set as "false".

Public Function ProcessLabel(myValue As Object) As String
    If ((myValue Is DBNull.Value) = False) Then
        Dim thetruth As Boolean
        Dim myValueStr As String
        myValueStr = CStr(myValue)
        thetruth = String.Equals(myValueStr, "01/01/1900")
    End If
    Return myValue.ToString
End Function

I cannot attach images but I assure you, in myValueStr I have "01/01/1900".

Returning Function in VB.net

I have a problem in this code because I am not returning any thing!

It works Just as I want it without returning but when I return it crashes.

Can you please help?

Public Function Clear() As Boolean


    'resetting the variuabels to be ready for next Order


    ZYZZ = "0"
    VAT = "0"
    MAX = "0"

    'this code is 3 peices 

    'This is sitting ctrl as a new control
    Dim ctrl As Control = Me.GetNextControl(Me, True)



    '1- is to look for text box and change them to 0 after the button is pressed
    Do
        If TypeOf ctrl Is TextBox Then
            ctrl.Text = "0"
        End If
        ctrl = Me.GetNextControl(ctrl, True)

    Loop Until ctrl Is Nothing


    '2- it clears the list box
    OrderListBox.Items.Clear()

    'And uncheck the check boxes
    LoyalCheckBox.Checked = False
    TakeAwayCheckBox.Checked = False


    'Finally it resets the Price, VAT, Total in the UI 

    Label6.Text = "£" & " " & "0"
    Label7.Text = "£" & " " & "0"
    Label8.Text = "£" & " " & "0"

    'Clearing the array to prepare for next order

    arr.Clear()



End Function

Also same problem in this code!

Private Function calculate() As Boolean


    '=================================='

    ZYZZ = 0

    For i As Integer = 0 To arr.Count - 1

        ZYZZ = ZYZZ + arr(i)

    Next i

    '=================================='


    '=================================='

    If LoyalCheckBox.Checked = True Then

        CardT = ZYZZ * card

    Else
        CardT = "0"

    End If

    If TakeAwayCheckBox.Checked = True Then

        TAF = ZYZZ * TA


    Else
        TAF = "0"
    End If

    '=================================='

    VAT = ZYZZ * cVAT

    MAX = ZYZZ - (CardT + TAF) + VAT


    Label6.Text = "£" & " " & ZYZZ

    Label7.Text = "£" & " " & VAT

    Label8.Text = "£" & " " & MAX



End Function

I have looked up online but I did not understand the methods they are using that's why its better to ask a direct question, thank you.

Loop through TableRow.Cells

Say I have a table like this:

<html xmlns="http://ift.tt/lH0Osb" >
<head id="Head1" runat="server">
    <title>TableCell Example</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    <h1>TableCell Example</h1>
    <asp:table id="Table1" runat="server" 
        CellPadding="3" CellSpacing="3"
        Gridlines="both">
        <asp:TableRow>
            <asp:TableCell Text="(0,0)" />
            <asp:TableCell Text="(0,1)" />
            <asp:TableCell Text="(0,2)" />
        </asp:TableRow>
        <asp:TableRow>
            <asp:TableCell Text="(1,0)" />
            <asp:TableCell Text="(1,1)" />
            <asp:TableCell Text="(1,2)" />
        </asp:TableRow>
    </asp:table>

    </div>
    </form>
  </body>
</html>

How can I get the value of a cell in code. Something like this:

For Each row As TableRow In objTable.Rows
  'How do I get the value of a cell here by ID?
Next

Can you get a cell value by index?

Unable to send mail from VB form using system.net.mail

Our company has a call centre which pc's are locked down (no access to internet, email, office applications) and there is a need for them to be able to log support tickets from their own machines.

I have created a VB Windows forms application which grabs some info from the user (name, email, extension, subject and description of the issue) as well as system information collected from WMI.

I intent to send all of this information to our helpdesk via email, the sys information would enable us to identify hardware problems and such.

However when trying to send a mail. it just doesnt work.

We have a smtp relay which allows for anonymous email relay and does not require user credentials.

Once i get the basic test mail to work i will start populating the mail with the information i get from the user. However the mail is currently throwing exceptions and not sending at all.

Note I am an absolute beginner when it comes to VB and .net as i come from a linux / php background

Below is my code:

Imports System.Management
Imports System.Management.Instrumentation
Imports System.Net.Mail

Public Class Form1

    Private Property strComputer As String
    Private Property objWMIService As Object
    Private Property colItems As Object
    Private Property colComputers As Object
    Private Property strComputerRole As String
    Private Property colDisks As Object
    Private Property colOperatingSystems As Object
    Private Property IPConfigSet As Object

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Dim response As MsgBoxResult
        response = MsgBox("Are you sure you want to exit?", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Confirm")
        If response = MsgBoxResult.Yes Then
            Me.Dispose()
        ElseIf response = MsgBoxResult.No Then
            Exit Sub
        End If
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim strName As String
        Dim strDept As String
        Dim strEmail As String
        Dim strExt As String
        Dim strDesc As String
        Dim strAffect As String
        Dim strSubject As String

        strName = TextBox1.Text
        strDept = TextBox2.Text
        strEmail = TextBox3.Text
        strExt = TextBox4.Text
        strSubject = TextBox6.Text
        strDesc = RichTextBox1.Text
        strAffect = TextBox5.Text

        strComputer = "."
        objWMIService = GetObject("winmgmts:" _
            & "{impersonationLevel=impersonate}!\\" _
            & strComputer & "\root\cimv2")
        colItems = objWMIService.ExecQuery _
            ("Select * from Win32_ComputerSystem")
        For Each objItem In colItems
            TextBox7.Text = objItem.Name
            TextBox8.Text = objItem.Manufacturer
            TextBox9.Text = objItem.Model
            TextBox11.Text = objItem.TotalPhysicalMemory
        Next
        colComputers = objWMIService.ExecQuery _
    ("Select DomainRole from Win32_ComputerSystem")
        For Each objComputer In colComputers
            Select Case objComputer.DomainRole
                Case 0
                    strComputerRole = "Standalone Workstation"
                Case 1
                    strComputerRole = "Member Workstation"
                Case 2
                    strComputerRole = "Standalone Server"
                Case 3
                    strComputerRole = "Member Server"
                Case 4
                    strComputerRole = "Backup Domain Controller"
                Case 5
                    strComputerRole = "Primary Domain Controller"
            End Select
            TextBox10.Text = strComputerRole
        Next
        colItems = objWMIService.ExecQuery("Select * from Win32_Processor")
        For Each objItem In colItems
            TextBox12.Text = objItem.Manufacturer
            TextBox13.Text = objItem.Name
            TextBox14.Text = objItem.MaxClockSpeed & " MHz"
        Next
        colItems = objWMIService.ExecQuery("Select * from Win32_BIOS")
        For Each objItem In colItems
            TextBox15.Text = objItem.Version
            TextBox16.Text = objItem.SerialNumber
        Next
        colItems = objWMIService.ExecQuery("Select * from Win32_VideoController")
        For Each objItem In colItems
            TextBox17.Text = objItem.Name
        Next
        colDisks = objWMIService.ExecQuery("Select * from Win32_LogicalDisk where DeviceID = ""C:""")
        For Each objDisk In colDisks
            TextBox18.Text = Math.Round(objDisk.Size / 1073741824) & " GB"
            TextBox19.Text = Math.Round(objDisk.Freespace / 1073741824) & " GB"
        Next
        colOperatingSystems = objWMIService.ExecQuery("Select * from Win32_OperatingSystem")
        For Each objOperatingSystem In colOperatingSystems
            TextBox20.Text = objOperatingSystem.Caption & "  " & objOperatingSystem.Version
            TextBox21.Text = objOperatingSystem.ServicePackMajorVersion & "." & objOperatingSystem.ServicePackMinorVersion
        Next
        Dim moIP As ManagementObject

        Dim myNet = New ManagementObjectSearcher _
        ("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = True")

        For Each moIP In myNet.Get
            ' Eg: Display IP address in Message Box
            TextBox22.Text = moIP("IPAddress")(0)
        Next

        Dim mail As New MailMessage()
        mail.To.Add("helpdesk@company.co.za")
        mail.From = New MailAddress(strEmail)

        Dim smtp As New SmtpClient()
        smtp.Host = "relay.company.local"
        smtp.EnableSsl = False

        mail.Subject = strSubject
        mail.Body = strDesc
        smtp.Send(mail)

    End Sub

    Private Function Wscript() As Object
        Throw New NotImplementedException
    End Function

    Private Function IsNull(p1 As Object) As Boolean
        Throw New NotImplementedException
    End Function


End Class

UPDATE: Below is an exception

An unhandled exception of type 'System.Net.Mail.SmtpException' occurred in System.dll

Additional information: Service not available, closing transmission channel. The server response was: 4.3.2 Service not available, closing transmission channel

Autofill username password web form

I'm developing program and I'm using Skybound Gecko browser ! i want to inter the username and password automatically when i open the page!

I'm using this code to do this :

Private Sub login_Click(sender As Object, e As EventArgs) Handles login.Click
GeckoWebBrowser1.Document.GetElementById("codeTerminal").SetAttribute("value", "xxxxxx")
GeckoWebBrowser1.Document.GetElementById("userName").SetAttribute("value", "xxxxxx")
GeckoWebBrowser1.Document.GetElementById("pass").SetAttribute("value", "xxxxxx")

End Sub i test this on google and on Facebook its work !! but not working with the site i want :(

this is the site : http://ift.tt/1K09tzM

when i use the above code i face this error :

An unhandled exception of type 'System.NullReferenceException' occurred in Noor Phone.exe

Additional information: Object reference not set to an instance of an object.

this the web page text information :

1-"<"input name="codeTerminal" type="text" id="codeTerminal" style="float:left;display:inline;background-image:url('imges/login_box_white.png');width:243px;height:44px;background-repeat:no-repeat;border:none;line-height:44px;">"

2-"<"input name="userName" type="text" id="userName" style="float:left;display:inline;background-image:url('imges/login_box_white.png');width:243px;height:44px;background-repeat:no-repeat;border:none;line-height:44px;">

3-"<"input name="pass" type="password" id="pass" style="float:left;display:inline;background-image:url('imges/login_box_white.png');width:243px;height:44px;background-repeat:no-repeat;border:none;line-height:44px;">

how i can fix this i want this so badly

any help please..

Obsolete XML/XSD validation classes and functions

I'm trying to manipulate some code to first validate an XSD schema and then a XML file against that schema. I cannot cause the XML file to fail despite entering rogue values so I think that maybe an obsolete class and function are not functioning as they should (XmlValidatingReader & Compile). Can anyone suggest some code that would be fit for purpose here?

Private Function validatexml(ByVal infile As String) As Boolean
    'First we create the xmltextreader
    Dim xmlr As New XmlTextReader(infile)
    'Pass the xmltextreader into the xmlvalidatingreader
    'This will validate the xml doc with the schema file
    'The xml file itself points to the schema file
    Dim xmlvread As New XmlValidatingReader(xmlr)  'obsolete!!!!!

    'Set the validation event handler
    AddHandler xmlvread.ValidationEventHandler, AddressOf ValidationCallBack
    m_Success = True 'make sure to reset the success var

    'Read XML data
    While (xmlvread.Read)
    End While
    'Close the reader.
    xmlvread.Close()

    'The validationeventhandler is the only thing that would set m_Success to false
    Return m_Success
End Function


Private Sub ValidationCallBack(ByVal sender As Object, ByVal args As ValidationEventArgs)
    'Display the validation error.  This is only called on error
    m_Success = False 'Validation failed
    writertbox("Validation error: " + args.Message)
End Sub


Private Function validateSchema(ByVal infilename As String) As Boolean
    'this function will validate the schema file (xsd)
    Dim sr As StreamReader
    Dim myschema As XmlSchema
    m_Success = True
    Try
        sr = New StreamReader(infilename)
        myschema = XmlSchema.Read(sr, AddressOf ValidationCallBack)
        'This compile statement is what ususally catches the errors
        myschema.Compile(AddressOf ValidationCallBack) 'obsolete!!!!!
    Finally
        sr.Close()
    End Try
    Return m_Success
End Function

Modal Value, and Repetition

I want to make a modal value calculator, So it calculates the Modal value and its repetition

The idea is to make a list of data and its repetition like shown in any Graph.

This is code you I start with:

Public Class

Dim a1(100), a2(100), Rep(100), RepMer(100), AMer(100) As Single, n, count, m As Single, z, k, c, mars As Integer
    n = InputBox("How many data?", "RepTest")

    count = 0

    For count = 0 To n - 1
        a1(count) = InputBox("Add Value", "RepTest")
    Next

    z = n
    For run = 0 To n - 1
        mars = c
        z = z - 1
        k = 0
        For moon = 0 To (n - 1)

            If a1(z) = a1(moon) Then
                k = k + 1
                a2(run) = a1(z)
                Rep(run) = Rep(run) + k
                If Rep(run) > 2 Then
                    Rep(run) = Rep(run) - 1
                 End If

            End If
        Next

        MsgBox(a2(run)), , "Modal Value")
        MsgBox(Rep(run)),, "Repetition")

    Next

End Class

However, If you make the massage box outside the main 2nd loop, you have to make another loop with the same value 0 To (n-1), to match data position in an Array.

what I want you to help me please is:

I have to save the modal value and the repetition of one value in same position in the array, because if you use this code the output of n = 5 and enter value 2 ,2 ,2 ,1,1. the output will be 5 massage box with 3 equal for value 2, and 2 equal for value 1.

you can test by yourself copy the code and insert it to a form in VB.net.


With pictures:

see this link: Picture that describe the result

You can see that the output is more than one for each value, so How can I store the value and its repetition in one position in an array?


Thank you for reading, please I want a code answer. :)

DevExpress: Change cell background after its value is edited

How can I change the XtrsGrid's (GridControl) cell background after its value has been updated/changed/edited?

Can I do it in following event:

AddHandler grdView.RowCellStyle, AddressOf grdView_RowCellStyle

But this changes the color of whole Grid cells.

Private Sub grdView_RowCellStyle(sender As Object, e As RowCellStyleEventArgs)
    e.Appearance.BackColor = Color.Blue
End Sub

Contatenating two string

i want to merge two strings

example:

first string : www.org.a.org

second string: .org.lb

result string : www.org.a.org.lb

example:

first string : www.google.com

second string: google.com

result string : www.google.com

dim s1 as String = "www.org.a.org"
dim s2 as String = ".org.lb"
dim s2 as String = s1 & s2 ' www.org.a.org.org.lb !!

VB.NET merge 2 files

can anyone help. I want to search through 1 file for a specific string and replace that string with the content from another file from the same location, is this possible.?

Can I provide datasource=nothing form client side(javascript/jQuery) in VB.NET for checkboxlist?

I have a checkbox list in VB.NET. On page_load it will bind some data from the sql datasource. But, I want to make this checkbox list's datasource=nothing from the client side on focus event of the text box. Can i do this? If yes, then how?

fill the combobox with the column names

i have an application on vb.net with file Excel

First, i have a button "browse" which open a workbook Excel.

Second ,i have a button "get the names of the sheets" which give me the name of the sheet in a combobox1 ,then i choose the sheet. Then i have an other button " get the column names " which give me the name of the columns of the table in a combobox2 . When i select the name of the column a new sheet add named the name of the column and which has the data of this column

what i want is :

when i choose another sheet from combobox1, the combobox2 will be refresh with the new columns names of the new sheet

           Private Sub ComboBox2_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)

    Chargement_de_données.xlWorkSheet = CType(Chargement_de_données.xlWorkBook.Sheets(Chargement_de_données.ComboBox1.Text), Excel.Worksheet)
    Chargement_de_données.xlWorkSheet.Activate()
    Chargement_de_données.xlApp.Visible = True

    Dim key As String = CStr(DirectCast(ComboBox2.SelectedItem, KeyValuePair(Of Integer, String)).Key)
    Dim value As String = DirectCast(ComboBox2.SelectedItem, KeyValuePair(Of Integer, String)).Value

    DataGridView1.Visible = True

    Dim DoesSheetExists As Boolean = False

    For Each xs In Chargement_de_données.xlApp.Sheets
        If xs.Name = value Then
            DoesSheetExists = True
        End If
    Next
    If DoesSheetExists = True Then
        MsgBox("L'indicateur est déja ouvert ", CType(MessageBoxIcon.Error, MsgBoxStyle))
    Else
        With Chargement_de_données.xlWorkSheet

            Dim lastrow As Integer = Chargement_de_données.xlWorkSheet.Cells.Rows.End(XlDirection.xlDown).Row
            Dim colletter As String = ColumnIndexToColumnLetter(CInt(key))

            exWS2 = DirectCast(Chargement_de_données.xlWorkBook.Sheets.Add, Microsoft.Office.Interop.Excel.Worksheet)
            exWS2.Name = value

            Chargement_de_données.xlWorkSheet.Range("C1:C" & lastrow.ToString).Copy(exWS2.Range("A1"))

            Chargement_de_données.xlWorkSheet.Range(colletter & "1:" & colletter & lastrow.ToString).Copy(exWS2.Range("B1"))

vb.net using chart with serial port

I finished my project and everything work great, VB.net program read values right I want "chart" read the values from serial port and i want it to read the values 1/day Can someone help me in this! This is my code

Public Class frmDisplay2
    Dim comOpen As Boolean      'Keeps track of the port status. True = Open; False = Closed
    Dim readbuffer As String    'Buffer of whats read from the serial port

    Private Sub frmDisplay_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'Get all connected serial ports
        Dim comPorts As String() = System.IO.Ports.SerialPort.GetPortNames

        If comPorts.Count < 1 Then
            'If there are not ports connected, show an error and close the program.
            MsgBox("There are no com ports available! Closing program.")
            Me.Close()
        Else
            cmbPorts.Items.AddRange(comPorts)
            cmbPorts.Text = comPorts(0)
        End If
    End Sub

    Private Sub btnConnect_Click(sender As Object, e As EventArgs) Handles btnConnect.Click
        'Conenct to serial port
        DoConnect()
    End Sub

    Private Sub frmDisplay_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        'Gracefully disconnect before form closes
        DoDisconnect()
    End Sub

    Private Sub btnDisconnect_Click(sender As Object, e As EventArgs) Handles btnDisconnect.Click
        'Disconnect the serial port
        DoDisconnect()
    End Sub

    Private Sub SerialPort1_DataReceived(ByVal sender As System.Object, _
                                         ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) _
                                         Handles SerialPort1.DataReceived
        If comOpen Then

            Try
                'Send data to a new thread to update the temperature display
                readbuffer = SerialPort1.ReadLine()
                Me.Invoke(New EventHandler(AddressOf updateTemp))
            Catch ex As Exception
                'Otherwise show error. Will display when disconnecting.
                'MsgBox(ex.Message)
            End Try
        End If
    End Sub

    Public Sub updateTemp(ByVal sender As Object, ByVal e As System.EventArgs)
        'Update temperature display as it comes in
        Dim read As Decimal
        read = readbuffer.Replace(vbCr, "").Replace(vbLf, "")
        txtTemp.Text = read
        lstHistory.Items.Insert(0, read)

        'Check Highest Temp
        If txtHigh.Text < read Then
            txtHigh.Text = read
        End If

        'Check Lowest Temp
        If txtLow.Text > read Then
            txtLow.Text = read
        End If

        'Calculate Average
        Dim total As Decimal
        Dim count As Integer
        For Each temperature In lstHistory.Items
            total += temperature
            count = count + 1
        Next

        txtAverage.Text = total / count

        GroupBox2.Text = "History [" & count & "]" 'Running count of temperature reads. 

        total = 0 'Reset total
        count = 0 'Reset count
    End Sub

    Public Sub DoDisconnect()
        'Graceful disconnect if port is open
        If comOpen Then
            SerialPort1.DiscardInBuffer()
            SerialPort1.Close()

            'Reset our flag and controls
            comOpen = False
            btnDisconnect.Enabled = False
            btnConnect.Enabled = True
            txtBaudRate.Enabled = True
            cmbPorts.Enabled = True
        End If
    End Sub

    Public Sub DoConnect()
        'Setup the serial port connection
        With SerialPort1
            .PortName = cmbPorts.Text               'Selected Port
            .BaudRate = CInt(txtBaudRate.Text)      'Baud Rate. 9600 is default.
            .Parity = IO.Ports.Parity.None
            .DataBits = 8
            .StopBits = IO.Ports.StopBits.One
            .Handshake = IO.Ports.Handshake.None
            .RtsEnable = False
            .ReceivedBytesThreshold = 1
            .NewLine = vbCr
            .ReadTimeout = 10000
        End With

        'Try to open the selected port...
        Try
            SerialPort1.Open()
            comOpen = SerialPort1.IsOpen
        Catch ex As Exception
            comOpen = False
            MsgBox("Error Open: " & ex.Message)
        End Try

        btnDisconnect.Enabled = True
        btnConnect.Enabled = False
        txtBaudRate.Enabled = False
        cmbPorts.Enabled = False
    End Sub

    Private Sub cmbPorts_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbPorts.SelectedIndexChanged

    End Sub

    Private Sub txtTemp_TextChanged(sender As Object, e As EventArgs) Handles txtTemp.TextChanged

    End Sub

    Private Sub Chart1_Click(sender As Object, e As EventArgs) Handles Chart1.Click

    End Sub

    Private Sub txtHigh_TextChanged(sender As Object, e As EventArgs) Handles txtHigh.TextChanged

    End Sub

    Private Sub lstHistory_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstHistory.SelectedIndexChanged

    End Sub

    Private Sub txtAverage_TextChanged(sender As Object, e As EventArgs) Handles txtAverage.TextChanged

    End Sub
End Class

Validation in in textbox using visual basic

I am about to do validation on the textbox using vb..can someone help me how to validate if i leave the text empty using vb language? N how to validate the character, phone number and email?

    Imports System.Data
Imports System.Data.SqlClient
Imports System.IO
Imports System.Web.UI.WebControls


Partial Class _Default
    Inherits System.Web.UI.Page
    'Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("dbconnection").ConnectionString)`


Dim con As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\user\Documents\Visual Studio 2010\feedbackScholarInn\App_Data\Database.mdf;Integrated Security=True;User Instance=True")

        Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
            Dim date1 As Date = Date.Now
            con.Open()
            Dim cmd As New SqlCommand("insert into complainer(fullname,no_Tel,email) values(@fullname,@no_Tel,@email)", con)
            cmd.Parameters.AddWithValue("@fullname", txtFullname.Text)
            cmd.Parameters.AddWithValue("@no_Tel", txtno_Tel.Text)
            cmd.Parameters.AddWithValue("@email", txtEmail.Text)
            cmd.ExecuteNonQuery()
            con.Close()

            con.Open()
            Dim cmd2 As New SqlCommand("insert into feedbackDetails(message,subject,status,typeofFeedback,date,roomNo) values(@message,@subject,@status,@typeofFeedback,@date,@roomNo)", con)
            cmd2.Parameters.AddWithValue("@message", txtMessage.Text)
            cmd2.Parameters.AddWithValue("@status", "New")
            cmd2.Parameters.AddWithValue("@subject", txtSubject.Text)
            cmd2.Parameters.AddWithValue("@typeofFeedback", dropDownFeedback.SelectedValue)
            cmd2.Parameters.AddWithValue("@date", date1)
            cmd2.Parameters.AddWithValue("@roomNo", txtRoom.Text)
            cmd2.ExecuteNonQuery()


            con.Close()


        End Sub
    End Class

Rotate a picture box

I am working on a basic game to try and improve my visual basic skills. I have asked a previous question regarding this, however I am really stuck and don't know what I'm doing.

I originally thought the Visual Basic Powerpack shapes would be best, however I have now been informed that picture box is best so I have changed this in the form, however not in the code.

I would like a picture box to be rotated 90 degrees around its centre when it has been clicked on and the left or right arrow keys have been pressed (it doesn't really matter which button is pressed)

There will eventually be 60 line shapes, and I don't know how to adapt my existing code, I would really appreciate some help - I have tried to code this myself however I don't understand what I'm doing now.

Here is my code on the form with the shapes:

Public Class frmPlay

Private Sub frmPlay_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
    'pbox11.AllowDrop = True
    'pbox22.AllowDrop = True
    'pbox33.AllowDrop = True
    'pbox44.AllowDrop = True
    'pbox55.AllowDrop = True
    'pbox66.AllowDrop = True
    'pbox77.AllowDrop = True
    'pbox88.AllowDrop = True
End Sub

Private Sub pboxes_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles pbox1.MouseDown, pbox2.MouseDown, pbox3.MouseDown, pbox4.MouseDown, pbox5.MouseDown, pbox6.MouseDown, pbox7.MouseDown, pbox8.MouseDown
    Dim pb As PictureBox = DirectCast(sender, PictureBox)
    pb.DoDragDrop(pb.Image, DragDropEffects.Copy)
End Sub

Private Sub pboxes_DragOver(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles pbox11.DragOver, pbox22.DragOver, pbox33.DragOver, pbox44.DragOver, pbox55.DragOver, pbox66.DragOver, pbox77.DragOver, pbox88.DragOver
    If e.Data.GetDataPresent(DataFormats.Bitmap) Then
        e.Effect = DragDropEffects.Copy
    End If
End Sub

Private Sub pboxes_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles pbox11.DragDrop, pbox22.DragDrop, pbox33.DragDrop, pbox44.DragDrop, pbox55.DragDrop, pbox66.DragDrop, pbox77.DragDrop, pbox88.DragDrop
    If e.Data.GetDataPresent(DataFormats.Bitmap) Then
        Dim pb As PictureBox = DirectCast(sender, PictureBox)
        pb.Image = DirectCast(e.Data.GetData(DataFormats.Bitmap), Bitmap)
    End If
End Sub

Private Sub btnPause_Click(sender As System.Object, e As System.EventArgs) Handles btnPause.Click
    frmPause.ShowDialog()
End Sub

Private Sub RotateClockwise(ByVal line As LineShape)
    'Code to rotate the passed line clockwise here
    Dim x1 As Integer = line.X1
    Dim y1 As Integer = line.Y1
    Dim x2 As Integer = line.X2
    Dim y2 As Integer = line.Y2


End Sub

Private Sub RotateCounterclockwise(ByVal line As LineShape)

    'Code to rotate the passed line counter-clockwise here

End Sub

Private Sub LineShape_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs)
    'Which line?
    Dim line As LineShape = TryCast(sender, LineShape)
    If line Is Nothing Then Exit Sub

    'Left key?
    If e.KeyCode = Keys.Left Then RotateCounterclockwise(line)

    'Right key?
    If e.KeyCode = Keys.Right Then RotateClockwise(line)
End Sub
Private Sub frmPlay_Load_2(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

End Sub

End Class

If you can make any sense of this I would really appreciate it, thanks you for reading!

Read old and new values on RadGrid Batch Edit

I am trying to work on Batch Edit, I want to read the edited values only from the below events

I am not able to read the old and new values from RadGrid1_ItemUpdated(object source, GridUpdatedEventArgs e) as the below code which we use to read the old and new values contains e.CommandArgument which we don't get from GridUpdatedEventArgs

Dim argument As GridBatchEditingEventArgument = TryCast(e.CommandArgument, GridBatchEditingEventArgument)

Also, please help me how to get the old and new values from the detail(child or hierarchical) grid. I am facing problem to get from child grid.

Protected Sub radDataEntry_BatchEditCommand(sender As Object, e As Telerik.Web.UI.GridBatchEditingEventArgs) Handles radDataEntry.BatchEditCommand
        Dim newValues As Hashtable
        Dim oldValues As Hashtable
        For Each command As GridBatchEditingCommand In e.Commands
            If (command.Type = GridBatchEditingCommandType.Update) Then
                newValues = command.NewValues
                oldValues = command.OldValues
                Dim ID As String = newValues("ID").ToString()
            End If
        Next

    End Sub

How can I create a new thread AddressOf a function with parameters in VB?

When option strict is OFF, works fine. ON, I get overload resolution failure:

http://ift.tt/1FeXrBr

I'm new to threading .. a function without parameters seems just fine, but WITH parameters? Tough. How can I do this? I searched already and mostly see java/js only answering this question.

Passing inputs to VBScript from Windows Forms Application

I have created a small desktop application which allows users to log a call with our help desk without the need of a browser or email application (since it is locked down)

Within the form code i call a vbs script which collects system information from WMI and then send an email via outlook/cdo (still deciding on email method)

Below is my form code for the send button.

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim strName As String
        Dim strDept As String
        Dim strEmail As String
        Dim strExt As String
        Dim strDesc As String
        Dim strAffect As String

        strName = TextBox1.Text
        strDept = TextBox2.Text
        strEmail = TextBox3.Text
        strExt = TextBox4.Text
        strDesc = RichTextBox1.Text
        strAffect = TextBox5.Text

        System.Diagnostics.Process.Start("c:\Temp\Support.vbs")
        MessageBox.Show("Thank you!")
        Me.Close()
    End Sub

End Class

My problem now comes in with the vbscript code. i need to pass the input parameters from the above form (Name, dept, email address, etc) to the VBScript file to use in the email to support, but i have no idea how to do this.

NOTE: I have very basic vbscript and vb experience and google is my friend, i have searched the internet for 2 days to find a solution but to no avail. So naturally this is my last resource

Below is my VBScript file, (support.vbs) which is called by the above form. Its copy and paste code with modification.

Set objNetwork = CreateObject("Wscript.Network")
strComputer = objNetwork.ComputerName
Set Arg = WScript.Arguments

Const NUMBER_OF_ROWS = 19
Const NUMBER_OF_COLUMNS = 2

Set objWord = CreateObject("Word.Application")
objWord.Visible = true
Set objDoc = objWord.Documents.Add()

Set objRange = objDoc.Range()
objDoc.Tables.Add objRange, NUMBER_OF_ROWS, NUMBER_OF_COLUMNS
Set objTable = objDoc.Tables(1)
objTable.Cell(1,1).Range.Text = "System Information For: "
objTable.Cell(2,1).Range.Text = "Manufacturer"
objTable.Cell(3,1).Range.Text = "Model"
objTable.Cell(4,1).Range.Text = "Domain Type"
objTable.Cell(5,1).Range.Text = "Total Physical Memory"
objTable.Cell(6,1).Range.Text = "Processor Manufacturer"
objTable.Cell(7,1).Range.Text = "Processor Name"
objTable.Cell(8,1).Range.Text = "Processor Clock Speed"
objTable.Cell(9,1).Range.Text = "Bios Version"
objTable.Cell(10,1).Range.Text = "Serial Number"
objTable.Cell(11,1).Range.Text = "Video Controller"
objTable.Cell(12,1).Range.Text = "CD-ROM Manufacturer"
objTable.Cell(13,1).Range.Text = "CD-ROM Name"
objTable.Cell(14,1).Range.Text = "KeyBoard"
objTable.Cell(15,1).Range.Text = "Primary Drive Size"
objTable.Cell(16,1).Range.Text = "Primary Drive Space Available"
objTable.Cell(17,1).Range.Text = "Service Pack"
objTable.Cell(18,1).Range.Text = "Windows Version"
objTable.Cell(19,1).Range.Text = "IP Address"

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * from Win32_ComputerSystem")
For Each objItem in colItems
objTable.Rows.Add()
objTable.Cell(1, 2).Range.Text = UCase(strComputer)
objTable.Cell(2, 2).Range.Text = objItem.Manufacturer
objTable.Cell(3, 2).Range.Text = objItem.Model
Select Case objItem.DomainRole
Case 0 strComputerRole = "Standalone Workstation"
Case 1 strComputerRole = "Member Workstation"
Case 2 strComputerRole = "Standalone Server"
Case 3 strComputerRole = "Member Server"
Case 4 strComputerRole = "Backup Domain Controller"
Case 5 strComputerRole = "Primary Domain Controller"
End Select
objTable.Cell(4, 2).Range.Text = strComputerRole
objTable.Cell(5, 2).Range.Text = objItem.TotalPhysicalMemory/1048576 & " MB"
Next

Set colItems = objWMIService.ExecQuery("Select * from Win32_Processor")
For Each objItem in colItems
objTable.Cell(6, 2).Range.Text = objItem.Manufacturer
objTable.Cell(7, 2).Range.Text = objItem.Name
objTable.Cell(8, 2).Range.Text = Round(objItem.MaxClockSpeed) & " MHz"
Next

Set colItems = objWMIService.ExecQuery("Select * from Win32_BIOS")
For Each objItem in colItems
objTable.Cell(9, 2).Range.Text = objItem.Version
objTable.Cell(10, 2).Range.Text = objItem.SerialNumber
Next

Set colItems = objWMIService.ExecQuery("Select * from Win32_VideoController")
For Each objItem in colItems
objTable.Cell(11, 2).Range.Text = objItem.Name
Next

Set colItems = objWMIService.ExecQuery("Select * from Win32_CDROMDrive")
For Each objItem in colItems
objTable.Cell(12, 2).Range.Text = objItem.Manufacturer
objTable.Cell(13, 2).Range.Text = objItem.Name
Next

Set colItems = objWMIService.ExecQuery("Select * from Win32_Keyboard")
For Each objItem in colItems
objTable.Cell(14, 2).Range.Text = objItem.Caption
Next

Set colItems = objWMIService.ExecQuery("Select * from Win32_LogicalDisk Where DeviceID = ""C:""")
For Each objItem in colItems
objTable.Cell(15, 2).Range.Text = Round(objItem.Size /1073741824) & " GB"
Next

Set colDisks = objWMIService.ExecQuery ("Select * from Win32_LogicalDisk")
For Each objDisk in colDisks
objTable.Cell(16, 2).Range.Text = Round(objDisk.Freespace /1073741824) & " GB"    
Next

Set colOperatingSystems = objWMIService.ExecQuery ("Select * from Win32_OperatingSystem")
For Each objOperatingSystem in colOperatingSystems
objTable.Cell(17, 2).Range.Text = objOperatingSystem.ServicePackMajorVersion & "." & objOperatingSystem.ServicePackMinorVersion
Next

Set colOperatingSystems = objWMIService.ExecQuery ("Select * from Win32_OperatingSystem")
For Each objOperatingSystem in colOperatingSystems
objTable.Cell(18, 2).Range.Text = objOperatingSystem.Caption & "  " & objOperatingSystem.Version
Next


Set IPConfigSet = objWMIService.ExecQuery _
    ("Select IPAddress from Win32_NetworkAdapterConfiguration ")

For Each IPConfig in IPConfigSet
    If Not IsNull(IPConfig.IPAddress) Then 
        For i=LBound(IPConfig.IPAddress) _
            to UBound(IPConfig.IPAddress)
objTable.Cell(19, 2).Range.Text = IPConfig.IPAddress(i)
        Next
    End If
Next

objTable.AutoFormat(23)

objDoc.SaveAs("C:\Temp\Sysinfo.doc")

objWord.Quit

Set myOlApp = CreateObject("Outlook.Application")
Set myItem = myOlApp.CreateItem(olMailItem)
Set myAttachments = myItem.Attachments
myAttachments.Add "C:\Temp\Sysinfo.doc"
myItem.Display     '-- Optional --
myItem.To = "email address"
myItem.Subject = ""
myItem.Body = "Dear IT Support" & vbCRLF & vbCRLF & "Please assist with the following:" & vbCRLF & vbCRLF & "1. Requester info.: " & strName & vbCRLF & vbCRLF & "2. Brief summary of the issue and error message," & vbCRLF & vbCRLF & "3. Name of system or piece of IT equipment which is not working (eg: screen, keyboard, Internet, etc.)," & vbCRLF & vbCRLF & "3.1 Other issues: " & vbCRLF & vbCRLF & "3.3 Telephone call issues: Telephone number being dialed/received, time issue occurred, Ext. number where issue occurred," & vbCRLF & vbCRLF & "4. Number of users affected by the issue," & vbCRLF & vbCRLF & "5. Step by step replication details(from the login screen until issue occurred)."