|
Hi,
there is a way to get a display's DPI value through WMI, it is the "LogPixel" field you would need from the Win32_DisplayConfiguration class, so it gets stored for each display individually.
BTW: this retrieval is both Forms and WPF agnostic and does not need P/Inwoke or any Win32 API. However there is one drawback: the first WMI query does tend to take up to one second to execute.
Luc Pattyn [Forum Guidelines] [My Articles]
The quality and detail of your question reflects on the effectiveness of the help you are likely to get.
Show formatted code inside PRE tags, and give clear symptoms when describing a problem.
|
|
|
|
|
I got the answer from the WPF forum, where I cross-posted. Here is the code, and it is indeed WPF-specific as I knew it would have to be after getting a suggestion from a Windows Forms programmer on this forum. It is actually much more elegant than the Forms suggestion, one more indication of the superiority of WPF over Windows Forms. It is device-specific! So if Microsoft ever does get around to supporting individual DPI Scalings per monitor, this code will work without change.
Consider the following code snippet:
_left = Monitor.Rect.left;
_top = Monitor.Rect.top;
_width = Monitor.Width;
_height = Monitor.Height;
Matrix m = PresentationSource.FromVisual(this).CompositionTarget.TransformToDevice;
double dpiX = m.M11;
double dpiY = m.M22;
_left /= dpiX;
_top /= dpiY;
_width /= dpiX;
_height /= dpiY;
The original values of _left, _top, _width and _height are the direct result of the monitor properties of the monitor the code is going to display images on. dpiX and dpiY are then the DPI scaling factors of the X and Y directions of that monitor. for 96 DPI (the standard) the values are 1.0. For 120 DPI, the values are 1.25. So I just scale the four monitor dimensions and Voila! Absolute perfection for this particular monitor.
End of story.
|
|
|
|
|
At the MSDN forum a MVP posted a sample explaining HandleRef:
MyObject myObject = new MyObject();
IntPtr handle = myObject.GetHandle();
NativeMethods.SomeNativeFunction(handle);
I don't understand how the value of handle can become invalid, handle is of type IntPtr which is a value type living on the stack until the method where handle is defined returns.
|
|
|
|
|
stax76 wrote: handle is of type IntPtr which is a value type living on the stack
It's a pointer, meaning that it "points" to something else (usually a reference type). It could be pointing to a form, and that form may already have been disposed whilst the pointer is still there.
ForumSig
|
|
|
|
|
I think I get it now but still I think for the rare cases where something actually could get GC'ed it's much easier to keep a reference in order to prevent it to be collected by the GC instead of creating all this pointless HandleRef instances that will never be really needed. Some result but shorter code. For a library where it's not clear how the code will be used maybe it's more important.
|
|
|
|
|
There's quite some legacy-code that expects some complex structures as parameters, and you don't want them GC-ed while the method is executing. Those parameters are usually not referenced after the invoke of the unmanaged code and risk being cleaned up
|
|
|
|
|
Thanks for the help, if you or somebody else knows or stumbles upon some real world code sample showing this I would be glad to see it.
|
|
|
|
|
Any SendMessage call can use the HandleRef . That's the one that's used to crash the VB6-IDE.
There are some examples @StackOverflow[^].
|
|
|
|
|
Hi to all,
I am using Exchange server 2003 & Visual studio 2008
My project is read Unmails from mail server through Interop.MSXML2.dll and pass the mail values like (from,to,body,attachments) to my another application.
My mail server is my Organization server.
Now I read my Unread mails from my server.It shows the following Error Message.
"The remote server returned an error: (403) Forbidden."
Another time I re-run the same application it runs successfully.
now i change the mailserver mail id,First time it shows the the above message. & next time its works fine...
my Sample code:::
Sub XMLEMailWrite()
Dim loRequest As System.Net.HttpWebRequest
Dim loResponse As System.Net.HttpWebResponse
Dim loCredentials As System.Net.CredentialCache
Dim strLsrooturi, strLsquery As String
Dim laBytes() As Byte
Dim loRequestStream As System.IO.Stream
Dim loResponseStream As System.IO.Stream
Dim loXmlDoc As System.Xml.XmlDocument
Dim strpath As String = Path.GetFullPath(strXMLpath)
Dim fiPath As FileInfo = New FileInfo(strpath)
Try
If (fiPath.Exists) Then
File.Delete(strpath)
End If
strLsrooturi = strPathmail & strReadfolder
strLsquery = "<?xml version=""1.0""?>" & "<D:searchrequest xmlns = ""DAV:"" xmlns:m=""urn:schemas:httpmail:"">" & "<D:sql>SELECT ""urn:schemas:httpmail:hasattachment"", ""DAV:displayname"", ""urn:schemas:httpmail:from"", ""urn:schemas:httpmail:subject"",""urn:schemas:httpmail:textdescription"",""DAV:id"" FROM """ & strLsrooturi & """" & " WHERE ""urn:schemas:httpmail:read"" = false" & "</D:sql></D:searchrequest>"
loCredentials = New System.Net.CredentialCache
loCredentials.Add(New System.Uri(strLsrooturi), "NTLM", New System.Net.NetworkCredential(strUsername, strPassword, strDomain))
loRequest = CType(System.Net.WebRequest.Create(strLsrooturi), System.Net.HttpWebRequest)
loRequest.Credentials = loCredentials
loRequest.Method = "SEARCH"
laBytes = System.Text.Encoding.UTF8.GetBytes(strLsquery)
loRequest.ContentLength = laBytes.Length
loRequestStream = loRequest.GetRequestStream
loRequestStream.Write(laBytes, 0, laBytes.Length)
loRequestStream.Close()
loRequest.ContentType = "text/xml"
loRequest.Headers.Add("Translate", "F")
loResponse = CType(loRequest.GetResponse, System.Net.HttpWebResponse)
loResponseStream = loResponse.GetResponseStream
loXmlDoc = New System.Xml.XmlDocument
loXmlDoc.Load(loResponseStream)
loXmlDoc.Save(Path.GetFullPath(strXMLpath))
loResponseStream.Close()
Catch ex As Exception
Err.ErrorLog(strErrorfile, "XMLEMailWrite()", ex.Message)
End Try
End Sub
What is that problem & how to rectify that one?????
Pls help me...
thanks,
nkmkrishna
|
|
|
|
|
The remote server returned an error: (403) Forbidden, means just that. Your authentication failed, try using the right username and password.
If at first you don't succeed ... post it on The Code Project and Pray.
|
|
|
|
|
Hi ALL,
I am trying the same thing in C#. But i am getting the "login timeout error".
please let me know the reason or post ur sample code.
your code doesnt seems to be using Interop.MSXML ? or how to use the same ?
your help would be highly appreciated.
Regards.,
Veerasekar
Code :
~~~~~~~
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Xml;
namespace EmailReading
{
public class MailUtil
{
private CredentialCache creds = new CredentialCache();
public MailUtil()
{
}
/// <summary>
/// Gets all unread emails in a user's Inbox
/// </summary>
/// <returns>A list of unread mail messages</returns>
public List<model.Mail> GetUnreadMail()
{
List<model.Mail> unreadMail = new List<model.Mail>();
string reqStr =
@"<?xml version=""1.0""?>
<g:searchrequest xmlns:g=""DAV:"">
<g:sql>
SELECT
""urn:schemas:mailheader:from"", ""urn:schemas:httpmail:textdescription""
FROM
""
WHERE
""urn:schemas:httpmail:read"" = FALSE
AND ""urn:schemas:httpmail:subject"" = 'tbintg'
AND ""DAV:contentclass"" = 'urn:content-classes:message'
</g:sql>
</g:searchrequest>";
byte[] reqBytes = Encoding.UTF8.GetBytes(reqStr);
// set up web request
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://mail.Mycompany.com/Exchange/demo@Mycompany.com/Inbox/");
//request.Credentials = this.creds;
request.Credentials = new NetworkCredential("Demo", "password123","MyDomain");
request.Method = "SEARCH";
request.ContentLength = reqBytes.Length;
request.ContentType = "text/xml";
request.Timeout = 9000000;
using (Stream requestStream = request.GetRequestStream())
{
try
{
requestStream.Write(reqBytes, 0, reqBytes.Length);
}
catch
{
}
finally
{
requestStream.Close();
}
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
try
{
XmlDocument document = new XmlDocument();
document.Load(responseStream);
// set up namespaces
XmlNamespaceManager nsmgr = new XmlNamespaceManager(document.NameTable);
nsmgr.AddNamespace("a", "DAV:");
nsmgr.AddNamespace("b", "urn:uuid:c2f41010-65b3-11d1-a29f-00aa00c14882/");
nsmgr.AddNamespace("c", "xml:");
nsmgr.AddNamespace("d", "urn:schemas:mailheader:");
nsmgr.AddNamespace("e", "urn:schemas:httpmail:");
// Load each response (each mail item) into an object
XmlNodeList responseNodes = document.GetElementsByTagName("a:response");
foreach (XmlNode responseNode in responseNodes)
{
// get the <propstat> node that contains valid HTTP responses
XmlNode uriNode = responseNode.SelectSingleNode("child::a:href", nsmgr);
XmlNode propstatNode = responseNode.SelectSingleNode("descendant::a:propstat[a:status='HTTP/1.1 200 OK']", nsmgr);
if (propstatNode != null)
{
// read properties of this response, and load into a data object
XmlNode fromNode = propstatNode.SelectSingleNode("descendant: :from", nsmgr);
XmlNode descNode = propstatNode.SelectSingleNode("descendant::e:textdescription", nsmgr);
// make new data object
model.Mail mail = new model.Mail();
if (uriNode != null)
mail.Uri = uriNode.InnerText;
if (fromNode != null)
mail.From = fromNode.InnerText;
if (descNode != null)
mail.Body = descNode.InnerText;
unreadMail.Add(mail);
}
}
}
catch (Exception e)
{
string msg = e.Message;
}
finally
{
responseStream.Close();
}
}
return unreadMail;
}
}
}
|
|
|
|
|
Hi all,
In the project am doing in vb.net, i have five forms. A link from one form e.g form A to B ensures that form A is closed or hide and B is shown. And am using the form control values e.g textboxPatID, which is used for patient's ID, of form A in form B and other forms to access databse on other details about the patient like Lab,medical report etc.
Now my problem is; because form A is closed before form B opens, if I use the same value of patient ID repeatedly, an exception throws, indicating that "........make sure u've not released resources before trying to use it".
I used "public shared .." and "Private property" , to access the form value in form A from form B.
My question is this: How do I keep using this textbox value repeatedly while at the same time form A is closed?Any suggestion will be appreciated.
Thanks!
|
|
|
|
|
This is one of the reasons why having one form access controls on another form is generally discouraged. You should define a property on form B and set in in the code that moves from A to B. If that is not possible, you should be able to use an application level object outside of both forms that has a "CurrentPatientID" property or something similar.
|
|
|
|
|
I tried to use this property code in form B:
Public Property PassdText() As String<br />
Get 'stores the extracted value<br />
Return _pasdText<br />
End Get<br />
Set(ByVal value As String) 'assigns the extracted value to "_pasdText" variable<br />
_pasdText = value<br />
End Set<br />
End Property
And then used the following code in the button_click to access it in form A :
Dim vw As New vwPatient
vw.PassdText = sachTextBox.Text
but when it gets to form A, a null exception is raised for the first selected index. So what do i do?
(by the way am using tabcontrol in form B,so each time a tab page is selected, a query runs using the patientID)
The other suggestion about "application level object", I dont have a clue on how to do that.
Am not experienced in vb.net.
Thanks!
|
|
|
|
|
Where is the null reference exception happening? Is sachTextBox null? If so, the routine you are in may be being run before the form is completely loaded and you will need to check that the form is loaded (or that sachTextBox is not null) before this code runs. If not, you will need to find out what is null and figure out a way to get it initialized before trying to use it.
|
|
|
|
|
HI,
i hav a treeview and treenode... I want to get node values for specific node... i dont know how to iterate throught a specific node and get the node values...
here is my code....
TreeView permTree = new TreeView();
//populate permtree....
permTree.BeginUpdate();
permTree.Nodes.Add("Parent");
permTree.Nodes[0].Nodes.Add("Child 1");
permTree.Nodes[0].Nodes.Add("Child 2");
permTree.Nodes[0].Nodes[1].Nodes.Add("Grandchild");
permTree.Nodes[0].Nodes[1].Nodes[0].Nodes.Add("Great Grandchild");
permTree.EndUpdate();
TreeView tempTree = new TreeView();
tempTree.Nodes.Add("Project");
string roottext = permTree.Nodes[0].Text;
TreeNode node = permTree.Nodes[0];
int childCount = node.GetNodeCount(true);
int temp = node.GetNodeCount(false);
System.Data.DataTable[] tables = new System.Data.DataTable[childCount];
for (int i = 0; i < childCount; i++)
{
// string tempString = node.
}
cAn any one please help me to do so?
|
|
|
|
|
It sounds like you want to "walk the tree", in which case you'll really need a recursive method to do that (one that calls itself). In you case the method will return the text of the current node and then call itself passing each child node as a parameter.
I just love Koalas - they go great with Bacon.
|
|
|
|
|
Hi,
thanks for ur reply...
I cud hav recursive function. But i dont know how to loop through it. I mean, How to use nextnode method and loop through all the nodes in the treenode which has child nodes....
|
|
|
|
|
Hello friends,
I have a xmal file which contains all the javascript validation, section group ect fro my wep based application.I wanna use that file globally over my application.How can i include and access that file?
|
|
|
|
|
I've just recently ported a sockets client from .Net 2.0 to .Net 3.5 ...
and now it runs into reoccurring problems, of which I'm a little suspicious may be related to subtle differences between the frameworks that I'm not allowing for.
Specifically the Receive Callback function is being invoked, but the socket itself is no longer connected (and probably disposed). This is in spite of the fact that data is expected to be received.
private void ReceiveCallback(IAsyncResult ar)
{
SocketError sErr = SocketError.Success;
int bytesRead = 0;
lock (this)
{
try
{
Socket socket = (Socket)ar.AsyncState;
sErr = new SocketError();
bytesRead = socket.EndReceive(ar, out sErr);
...
And the essentials of the exception are:
ReceiveCallback threw an error. System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.Net.Sockets.Socket'.
at System.Net.Sockets.Socket.EndReceive(IAsyncResult asyncResult, SocketError& errorCode)
The associated socket error code is 10038 - which when you read its description isn't very helpful either.
Just to add to this the previous version of this client is still running and still connecting to the same server without issue.
My request is if anyone can point me in the right direction as to what I'm missing or doing wrong. You can reasonably assume that I've googled every permutation of the above in my quest.
Here's some possibilities:
* There's some subtle distinction in how v2.0 and v3.5 sockets connect (e.g. defaults for various socket options) that the server I'm connecting doesn't like / understand.
* It's a speed issue. The v2.0 code has got a whole heap of throttling tricks, that the v3.5 based version does not - I don't think this one's likely (already been playing around in this area).
* It's a threading and/or locks problem on the socket itself.
* I'm missing something important in using sockets - not likely, but this excuse is here for completeness, just in case you have some "traps for young players" type of insight.
* Or something else.
I just love Koalas - they go great with Bacon.
|
|
|
|
|
It sounds like your Socket object is being disposed! I would expect that putting a reference to it in your AsyncState would stop the GC collecting it, so are you disposing of it somewhere else?
I don't have a simple answer, but you could try this: Derive from Socket and override Dispose . Put a breakpoint in there to find out when it is being disposed and by whom.
Also, the code you posted has a couple of no-no's:
1) Locking on this is considered bad practice - use a private object to lock on.
2) You don't need to initialise sErr as it is passed as an out parameter.
Nick
----------------------------------
Be excellent to each other
|
|
|
|
|
Thanks for those suggestions Nick.
As to the bad practices, they actually originally came from sample code that I was trying as a part of resolving this problem. I left them in there in case it triggered someone's memory (and they had better suggestions).
I've already looked at the actual .Net sockets code so I understand some of the mechanisms involved. In particular it relates to the m_IntCleanedUp member and the code related to its handling. But it hasn't really told me what I need to know to resolve the above.
I just love Koalas - they go great with Bacon.
|
|
|
|
|
Thanks to Nick's suggestion Nick Butler wrote: Derive from Socket and override Dispose. .
I managed to find the fault when I overrode Disconnect and had it dump a stack trace.
The previous version of this service used WSE, the new version of this service uses WCF. In the previous version I had put a call to disconnect in the destructor to ensure that the socket got cleaned up properly. Under WCF the destructor was being invoked at an inopportune time resulting in the socket being disconnected (but not actually disposed).
Various aspects to the solution, but the two main ones were:
1. Remove the 'cleanup' call to disconnect from the destructor. i.e. If you're using my service then you call the disconnect yourself.
2. Supply the decoration [OperationBehavior(TransactionScopeRequired = true)] to each method exposed by the WCF service.
I just love Koalas - they go great with Bacon.
|
|
|
|
|
sfsgfgjhklj
gjgjgkk
k
jhjhfddserty
gdfgguijkk
|
|
|
|
|
chandni patel wrote: sfsgfgjhklj
gjgjgkk
k
jhjhfddserty
gdfgguijkkRose
What kind of Testing are you doing over here?
Please DONT SPAM. If you have some problem, then asked over here, everybody will try to help you. But don't SPAM in this healthy site.
|
|
|
|