|
Also have tried SmoApplication.EnumAvailableSqlServers();
0 results
|
|
|
|
|
Use a newer version of SMO.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
|
Need to change datatype of a variable without changing its value .
Suppose i need to change a : string a = "a1" to byte[]
But the value of the byte[] should have the same value i.e "a1"
|
|
|
|
|
Um...you can't, not really.
The problem is that a string is made of an array of chars, each of which is a 16 bit value in UNICODE, while an array of bytes contains 8 bit values.
You can get a byte stream which holds the data from the string:
string s = ...
byte[] bytes = System.Text.Encoding.Unicode.GetBytes(s); Or you can get an ASCII version which is more likely to work with more external applications:
string s = ...
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(s);
But an array of bytes is not an array of chars, and thus not a string.
And you definitely can't treat an array of bytes as a string!
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
I'm having an issue with my C# code. I m trying to insert data into my database from a form, unfortunately I keep getting issues with Object reference not set to an instance of an object.
Here s the code:
aspx
<asp:GridView runat="server" ID="gvNEW"
AutoGenerateColumns="False" BackColor="White" BorderColor="#DEDFDE"
BorderStyle="None" BorderWidth="1px" CellPadding="4"
EnableModelValidation="True" ForeColor="Black" GridLines="Vertical" >
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:TextBox runat="server" text='<%#Eval("Name") %>' ID="txtName" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Project">
<ItemTemplate>
<asp:TextBox runat="server" text='<%#Eval("Project") %>' ID="txtProject" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Tower">
<ItemTemplate>
<asp:TextBox runat="server" text='<%#Eval("Tower") %>' ID="txtTower" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FunctionalArea">
<ItemTemplate>
<asp:TextBox runat="server" text='<%#Eval("FunctionalArea") %>' ID="txtFunctionalArea" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ResourceName">
<ItemTemplate>
<asp:TextBox runat="server" text='<%#Eval("ResourceName") %>' ID="txtResourceName" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CATWResourceName">
<ItemTemplate>
<asp:TextBox runat="server" text='<%#Eval("CATWResourceName") %>' ID="txtCATWResourceName" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Org">
<ItemTemplate>
<asp:TextBox runat="server" text='<%#Eval("Org") %>' ID="txtOrg" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="IndicateifbillingFP">
<ItemTemplate>
<asp:TextBox runat="server" text='<%#Eval("IndicateifbillingFP") %>' ID="txtIndicateifbillingFP" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="IndicateifbillingTM">
<ItemTemplate>
<asp:TextBox runat="server" text='<%#Eval("IndicateifbillingTM") %>' ID="txtIndicateifbillingTM" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="DefaultFTE">
<ItemTemplate>
<asp:TextBox runat="server" text='<%#Eval("DefaultFTE") %>' ID="txtDefaultFTE" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Active">
<ItemTemplate>
<asp:TextBox runat="server" text='<%#Eval("Active") %>' ID="txtActive" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="PersonnelResourceType">
<ItemTemplate>
<asp:TextBox runat="server" text='<%#Eval("PersonnelResourceType") %>' ID="txtPersonnelResourceType" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCC99" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
</asp:GridView>
<br />
C#
protected void InsertButton_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
conn.Open();
foreach (GridViewRow row in gvNEW.Rows)
{
gvNEW.Columns.RemoveAt(0);
cmd.CommandText = "INSERT INTO StaffTracking (Project, Tower, Functional Area, ResourceName, CATWResourceName, Org, IndicateifBillingFP, IndicateifBillingTM, DefaultFTE, Active, PersonnelResourceType)" + " VALUES ( '" + ((TextBox)row.FindControl("txtProject")).Text + "', '" + ((TextBox)row.FindControl("txtTower")).Text + "', '" + ((TextBox)row.FindControl("txtFunctional Area")).Text + "', '" + ((TextBox)row.FindControl("txtResourceName")).Text + "', '" + ((TextBox)row.FindControl("txtCATWResourceName")).Text + "', '" + ((TextBox)row.FindControl("TxtOrg")).Text + "', '" + ((TextBox)row.FindControl("txtIndicateifBillingFP")).Text + "', '" +
((TextBox)row.FindControl("txtIndicateifBillingTM")).Text + "', '" + ((TextBox)row.FindControl("txtDefaultFTE")).Text + "', '" + ((TextBox)row.FindControl("txtActive")).Text + "', '" + ((TextBox)row.FindControl("txtPersonnelResourceType")).Text + "')";
int numRegs = cmd.ExecuteNonQuery();
}
conn.Close();
ResetInputForm();
} :sigh:
|
|
|
|
|
Your code is vulnerable to SQL Injection[^].
NEVER use string concatenation to build a SQL query. ALWAYS use a parameterized query.
protected void InsertButton_Click(object sender, EventArgs e)
{
const string Query = "INSERT INTO StaffTracking (Project, Tower, [Functional Area], ResourceName, CATWResourceName, Org, IndicateifBillingFP, IndicateifBillingTM, DefaultFTE, Active, PersonnelResourceType) VALUES (@Project, @Tower, @FunctionalArea, @ResourceName, @CATWResourceName, @Org, @IndicateifBillingFP, @IndicateifBillingTM, @DefaultFTE, @Active, @PersonnelResourceType)";
using (SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString))
using (SqlCommand command = new SqlCommand(Query, connection))
{
connection.Open();
foreach (GridViewRow row in gvNEW.Rows)
{
command.Parameters.AddWithValue("@Project", ((TextBox)row.FindControl("txtProject")).Text);
command.Parameters.AddWithValue("@Tower", ((TextBox)row.FindControl("txtTower")).Text);
command.Parameters.AddWithValue("@FunctionalArea", ((TextBox)row.FindControl("txtFunctional Area")).Text);
command.Parameters.AddWithValue("@ResourceName", ((TextBox)row.FindControl("txtResourceName")).Text);
command.Parameters.AddWithValue("@CATWResourceName", ((TextBox)row.FindControl("txtCATWResourceName")).Text);
command.Parameters.AddWithValue("@Org", ((TextBox)row.FindControl("TxtOrg")).Text);
command.Parameters.AddWithValue("@IndicateifBillingFP", ((TextBox)row.FindControl("txtIndicateifBillingFP")).Text);
command.Parameters.AddWithValue("@IndicateifBillingTM", ((TextBox)row.FindControl("txtIndicateifBillingTM")).Text);
command.Parameters.AddWithValue("@DefaultFTE", ((TextBox)row.FindControl("txtDefaultFTE")).Text);
command.Parameters.AddWithValue("@Active", ((TextBox)row.FindControl("txtActive")).Text);
command.Parameters.AddWithValue("@PersonnelResourceType", ((TextBox)row.FindControl("txtPersonnelResourceType")).Text);
command.ExecuteNonQuery();
command.Parameters.Clear();
}
}
ResetInputForm();
}
The NullReferenceException is most likely due to the fact that your code is removing the column at index 0 on each pass through the loop.
- On the first row, this will remove the
txtName control, which you don't use. - On the second row, it will remove the
txtProject control. As a result, row.FindControl("txtProject") will return null , and you'll get a NullReferenceException when you try to access its Text property.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Hey Norris,
please, for the love of cheese, first change your INSERT-statement to use Sql-Parameters, like I suggested you to do categorically in response to your first(?) post here. Simple example here: http://www.dotnetperls.com/sqlparameter[^]
- it prevents SQL-injection
- it makes your code more readable - for you and us
- it can prevent certain errors or make them easier to find
After you've done that there's a good chance the exception message will point to to the exact line so you'll see for yourself where the error is - otherwise please come back and post the reworked code and indicate the line at which the exception occurs.
You could also change it to instantiating the connection locally and using the connection and command object in using-blocks.
cheers, Sascha
If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson
|
|
|
|
|
That worked! Thanks Richard and Sascha. I will parameterized all of my code going forward.
I did get an error for this field: command.Parameters.AddWithValue("@DefaultFTE", ((TextBox)row.FindControl("txtDefaultFTE")).Text);
Because this field is decimal(8,3) and not nvarchar. Not a problem I was able to handle it.
One final question to all? Is there a way to fire off one method which in turn fire off another one? I'm doing an import and submit. I want the import to do the submit. O Can I include the SubmitButton_click code in the ImportButton_click code?
modified 29-May-15 16:10pm.
|
|
|
|
|
Norris Chappell wrote: Is there a way to fire off one method which in turn fire off another one? I'm doing an import and submit. I want the import to do the submit. O Can I include the SubmitButton_click code in the ImportButton_click code? Whenever you realize a requirement like this (needing the code that currently is "dedicated" to a certain place/event (SubmitButton_click) also in other situations) you should factor that code out into a separate method that can be used universally and gets all required inputs via arguments. Then you can call it from ImportButton_click and SubmitButton_click. No duplicate code and no weird codepaths (like calling SubmitButton_click from ImportButton_click).
If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson
|
|
|
|
|
Sascha,
Thanks again! I was able to figure my last question out.
Regards,
Norris
|
|
|
|
|
You're welcome!
If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson
|
|
|
|
|
Hi,
I have created a DLL class and added two UserControls in it, UC01 and UC02.
In my WinForm application, I want to reference to the DLL using:
Assembly objAsm = Assembly.LoadFrom(@"C:\UC_FILES\MyDLL.dll");
Now, how can I locate a specific user control from that DLL and add it using:
userControl.Controls.Add(selected_uc);
Thanks,
Jassim[^]
Technology News @ www.JassimRahma.com
|
|
|
|
|
By "Reflection". Use the GetTypes method of the assembly, and then iterate thru the returned array till you found your type. Then Invoke its constructor (GetConstructor ) to get an instance which you cast to the desired type.
|
|
|
|
|
Im working on video streaming using mvc3 c# ,html5 and jquery and im sorry i cant post that code,
Now i want to update that to support any kind of video format and im ready to rewrite the entire code if required. can you guys tell me which open source plugin supports nearly any video format (included jquery/javascript video plugin and c# streaming code) and thanks in advance
modified 29-May-15 6:34am.
|
|
|
|
|
Message Closed
modified 1-Jun-15 8:55am.
|
|
|
|
|
way too much code man. You can add a small snippet, but nobody will read this much code.
What is the exact problem and what did you already try to solve that problem?
|
|
|
|
|
I'm not going to wade through that lot trying to work out what might be missing and what might not - it's not a good use of my time.
So help us to help you: edit your question, delete the code, and explain in English what you need help with. Then add small code fragments (enclosed in <pre> tags via the code widget to preserve the formatting) where they help your description.
But just dumping your code on us is rude, unhelpful, and very unlikely to get you the result you want.
Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...
|
|
|
|
|
How to add Microsoft.Sharepoint.WebControls in C# Windows Application??
|
|
|
|
|
You can add a reference to the assembly like any other, but you can't reuse WebControls in a WinForms application.
..well, theoretically you could show them in a browser-control; but that would require a webserver, and those controls to be created on the server, shown in the browser - would make communication rather hard.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
===========================================
EDIT: I would like to mention i am new to programming forums, i screwed this one up as i was frustrated, and really didn't have a direct question. I hope i can improve my manners in the future.
Sorry MCM
===========================================
So let me start out with i am new to C# but not to programming in general. Mostly PHP background.
That being said, i am currently designing "Client", "Server" application. The server reads the COM port for a string, parse's it, inserts it into the database, then sends the client the id of the database entry over Asynchronous TCP. This happens randomly there is no rhyme or reason for when the Serial stream is received.
That being said, it is very important that the TCP transfer of the id is not being delayed at all, seconds really count in this application.
The problem I am having is users are logging off their computer and "Force Closing" the client before it has a chance to send the disconnect command to the server. When this happens the client cannot reconnect until i reset the server's client list.
I would like to implement a "Heartbeat" command, lets say server sends ping to a number of clients (currently three for QA, eventually between 50-100 clients) and the client returns pong meaning the connection is alive. If the client fails to respond within the limit (say 30 seconds to a minute) i would like to remove it from the client list.
But once again this cannot interrupt the main function of this software which is sending the id to the clients and would have to run as a background thread.
I am not familiar enough with background threads (or threads in general really) to make this happen, and after a week of reading and research i am still unsure of my ability to do such a thing within a reasonable amount of time.
I seek help in this matter, if anyone could direct me to a good article, or give me a snippet to start with i would greatly appreciate it.
This section of code is based heavily upon the following article:
A Chat Application Using Asynchronous TCP Sockets[^]
This is probably the reason for me not understanding this as well as i should, i cheated and manipulated this code to do what i needed. I didn't see the need to reinvent the wheel to send a couple digits over TCP, a few times a day.
Let me also note that this "Server Code" runs as a windows service on a server, the client is a Windows Form application.
In the Following Code the sendHeartBeat() method and command.Heartbeat have not actually been implemented, they are the start of my code for it.
Also i have removed the logging code for ease of reading, as my logging methods are a little robust but work well for my needs.
the server side TCP Class code is as follows:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace mgMapsServer.Classes
{
enum Command
{
Login,
Logout,
callLog,
heartbeat,
Reset,
Null
}
public class TCPConnector
{
struct ClientInfo
{
public Socket socket;
public string strName;
}
struct HBInfo
{
public Socket socket;
public int index;
}
ArrayList clientList;
Socket serverSocket;
ArrayList HeartbeatList;
byte[] byteData = new byte[1024];
public TCPConnector()
{
clientList = new ArrayList();
HeartbeatList = new ArrayList();
try
{
serverSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, Convert.ToInt32(Library.sqlVars("serverPort")));
serverSocket.Bind(ipEndPoint);
serverSocket.Listen(4);
serverSocket.BeginAccept(new AsyncCallback(OnAccept), null);
\*Logging Code*\
}
catch (Exception ex) { \*Logging Code*\ }
}
}
private void OnAccept(IAsyncResult ar)
{
try
{
Socket clientSocket = serverSocket.EndAccept(ar);
serverSocket.BeginAccept(new AsyncCallback(OnAccept), null);
clientSocket.BeginReceive(byteData, 0,
byteData.Length, SocketFlags.None,
new AsyncCallback(OnReceive), clientSocket);
}
catch (Exception ex) { \*Logging Code*\ }
}
private void OnReceive(IAsyncResult ar)
{
try
{
Socket clientSocket = (Socket)ar.AsyncState;
clientSocket.EndReceive(ar);
Data msgReceived = new Data(byteData);
Data msgToSend = new Data();
msgToSend.cmdCommand = msgReceived.cmdCommand;
msgToSend.strName = msgReceived.strName;
switch (msgReceived.cmdCommand)
{
case Command.heartbeat:
break;
case Command.Reset:
\*Logging Code*\
int rIndex = 0;
foreach (ClientInfo client in clientList)
{
clientList.RemoveAt(rIndex);
++rIndex;
}
break;
case Command.Login:
ClientInfo clientInfo = new ClientInfo();
clientInfo.socket = clientSocket;
clientInfo.strName = msgReceived.strName;
clientList.Add(clientInfo);
msgToSend.strMessage = "<<<" + msgReceived.strName + " has Connected to the Server>>>";
break;
case Command.Logout:
int nIndex = 0;
foreach (ClientInfo client in clientList)
{
if (client.socket == clientSocket)
{
clientList.RemoveAt(nIndex);
break;
}
++nIndex;
}
clientSocket.Close();
msgToSend.strMessage = "<<<" + msgReceived.strName + " has Disconnected from the server>>>";
break;
}
if ((msgReceived.cmdCommand != Command.heartbeat) || (msgReceived.cmdCommand != Command.heartbeat))
{
\*Logging Code*\
}
if (msgReceived.cmdCommand != Command.Logout) { clientSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(OnReceive), clientSocket); }
}
catch (Exception ex) { \*Logging Code*\ }
}
public string callLogIDSender
{
get { return null; }
set { SendcallLogID(value); }
}
public void SendcallLogID(string ID)
{
try
{
Data msgToSend = new Data();
byte[] message;
msgToSend.cmdCommand = Command.callLog;
msgToSend.strMessage = ID;
message = msgToSend.ToByte();
\*Logging Code*\
foreach (ClientInfo clientInfo in clientList)
{
clientInfo.socket.BeginSend(message, 0, message.Length, SocketFlags.None,
new AsyncCallback(OnSend), clientInfo.socket);
}
}
catch (Exception ex) { \*Logging Code*\ }
}
public void sendHeartBeat()
{
try
{
Data msgToSend = new Data();
byte[] message;
msgToSend.cmdCommand = Command.heartbeat;
msgToSend.strMessage = null;
message = msgToSend.ToByte();
int nIndex = 0;
foreach (ClientInfo clientInfo in clientList)
{
HBInfo tempHB = new HBInfo();
tempHB.index = nIndex;
tempHB.socket = clientInfo.socket;
HeartbeatList.Add(tempHB);
clientInfo.socket.BeginSend(message, 0, message.Length, SocketFlags.None,
new AsyncCallback(OnSend), clientInfo.socket);
++nIndex;
}
}
catch (Exception e) { \*Logging Code*\ }
}
public void OnSend(IAsyncResult ar)
{
try
{
Socket client = (Socket)ar.AsyncState;
client.EndSend(ar);
}
catch (Exception ex)
{
\\Logging Code
}
}
}
class Data
{
public Data()
{
this.cmdCommand = Command.Null;
this.strMessage = null;
this.strName = null;
}
public Data(byte[] data)
{
this.cmdCommand = (Command)BitConverter.ToInt32(data, 0);
int nameLen = BitConverter.ToInt32(data, 4);
int msgLen = BitConverter.ToInt32(data, 8);
if (nameLen > 0)
this.strName = Encoding.UTF8.GetString(data, 12, nameLen);
else
this.strName = null;
if (msgLen > 0)
this.strMessage = Encoding.UTF8.GetString(data, 12 + nameLen, msgLen);
else
this.strMessage = null;
}
public byte[] ToByte()
{
List<byte> result = new List<byte>();
result.AddRange(BitConverter.GetBytes((int)cmdCommand));
if (strName != null)
result.AddRange(BitConverter.GetBytes(strName.Length));
else
result.AddRange(BitConverter.GetBytes(0));
if (strMessage != null)
result.AddRange(BitConverter.GetBytes(strMessage.Length));
else
result.AddRange(BitConverter.GetBytes(0));
if (strName != null)
result.AddRange(Encoding.UTF8.GetBytes(strName));
if (strMessage != null)
result.AddRange(Encoding.UTF8.GetBytes(strMessage));
return result.ToArray();
}
public string strName;
public string strMessage;
public Command cmdCommand;
}
modified 31-May-15 3:31am.
|
|
|
|
|
Member 11700380 wrote: That being said, it is very important that the TCP transfer of the id is not
being delayed at all, seconds really count in this application. If that is truly important, than you cannot work with Windows; the OS decides which application gets resources.
"As fast as possible" is something different, that one can do.
Do take not that a backgroundworker usually has a lower priority then the overall process. Since sending an ID should not stop the server from reading its comport, that would be a good idea.
I've seen the start of the code, but not a specific question. Do you have a list of active users that you can check if the heartbeat returns? How do you identify who's heartbeat is coming back (assuming multiple clients)?
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
When the Client sends data to the server, the computer name is encoded with the message. This is how i distinguish between machines.
Also, "as fast as possible" will have to do. I was very frustrated the other night when i wrote the original post.
Specific Question: I need some Good research material on a background threading, I have read everything i could find over the past week, and still feel i am coming up short on fully understanding implementing threads safely and properly.
I have a working prototype running in a sandbox currently, I just keep reading about how difficult thread problems are to diagnose, and am afraid to implement them into my code, work on it for a few weeks, then come to find out i broke my code by threading incorrectly.
I think i am just to the point where i need to trust my code, and go for it.
|
|
|
|
|
Do you have any locking where the thread accesses shared resources or an invoke-pattern to return the results?
How about you post your new code?
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
I have implemented a more in depth logging of the "TCP log in" process on both the client and the server side, i am going to give it a couple of days, to give my QA a chance to experience the errors i have been receiving from forced closes and attempts to reconnect and revisit this problem.
i feel i am making a mountain out of a mole hill...
I will reply to this post when i have some information that i fell will help me move forward with this problem, which hopefully will help someone in the future.
Also the server side code in question that i am running in my sandbox was included in the original post, listed under "heartbeat" in both the received data and its own method. All i did was place it in a separate application that user input is simulated using a database of user entries. So far so good, but i feel i am missing something far more simple than the problem i am trying to fix maybe i can figure a way to avoid the heartbeat all together...
As I said, i am going to give it a few days and review the logs to see what is "Really" going on.
|
|
|
|
|