Search Results

Search found 2946 results on 118 pages for 'ex umbris'.

Page 11/118 | < Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >

  • HttpWebRequest is extremely slow!

    - by Earlz
    Hello, I am using an open source library to connect to my webserver. I was concerned that the webserver was going extremely slow and then I tried doing a simple test in Ruby and I got these results Ruby program: 2.11seconds for 100 HTTP GETs C# library: 20.81seconds for 100 HTTP GETs I have profiled and found the problem to be this function: private HttpWebResponse GetRawResponse(HttpWebRequest request) { HttpWebResponse raw = null; try { raw = (HttpWebResponse)request.GetResponse(); //This line! } catch (WebException ex) { if (ex.Response is HttpWebResponse) { raw = ex.Response as HttpWebResponse; } } return raw; } The marked line is takes over 1 second to complete by itself while the ruby program making 1 request takes .3 seconds. I am also doing all of these tests on 127.0.0.1, so network bandwidth is not an issue. What could be causing this huge slow down?

    Read the article

  • The remote server returned an error: (400) Bad Request - uploading less 2MB file size?

    - by fiberOptics
    The file succeed to upload when it is 2KB or lower in size. The main reason why I use streaming is to be able to upload file up to at least 1 GB. But when I try to upload file with less 1MB size, I get bad request. It is my first time to deal with downloading and uploading process, so I can't easily find the cause of error. Testing part: private void button24_Click(object sender, EventArgs e) { try { OpenFileDialog openfile = new OpenFileDialog(); if (openfile.ShowDialog() == System.Windows.Forms.DialogResult.OK) { string port = "3445"; byte[] fileStream; using (FileStream fs = new FileStream(openfile.FileName, FileMode.Open, FileAccess.Read, FileShare.Read)) { fileStream = new byte[fs.Length]; fs.Read(fileStream, 0, (int)fs.Length); fs.Close(); fs.Dispose(); } string baseAddress = "http://localhost:" + port + "/File/AddStream?fileID=9"; HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(baseAddress); request.Method = "POST"; request.ContentType = "text/plain"; //request.ContentType = "application/octet-stream"; Stream serverStream = request.GetRequestStream(); serverStream.Write(fileStream, 0, fileStream.Length); serverStream.Close(); using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { int statusCode = (int)response.StatusCode; StreamReader reader = new StreamReader(response.GetResponseStream()); } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } Service: [WebInvoke(UriTemplate = "AddStream?fileID={fileID}", Method = "POST", BodyStyle = WebMessageBodyStyle.Bare)] public bool AddStream(long fileID, System.IO.Stream fileStream) { ClasslLogic.FileComponent svc = new ClasslLogic.FileComponent(); return svc.AddStream(fileID, fileStream); } Server code for streaming: namespace ClasslLogic { public class StreamObject : IStreamObject { public bool UploadFile(string filename, Stream fileStream) { try { FileStream fileToupload = new FileStream(filename, FileMode.Create); byte[] bytearray = new byte[10000]; int bytesRead, totalBytesRead = 0; do { bytesRead = fileStream.Read(bytearray, 0, bytearray.Length); totalBytesRead += bytesRead; } while (bytesRead > 0); fileToupload.Write(bytearray, 0, bytearray.Length); fileToupload.Close(); fileToupload.Dispose(); } catch (Exception ex) { throw new Exception(ex.Message); } return true; } } } Web config: <system.serviceModel> <bindings> <basicHttpBinding> <binding> <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="2097152" maxBytesPerRead="4096" maxNameTableCharCount="2097152" /> <security mode="None" /> </binding> <binding name="ClassLogicBasicTransfer" closeTimeout="00:05:00" openTimeout="00:05:00" receiveTimeout="00:15:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="67108864" maxReceivedMessageSize="67108864" messageEncoding="Mtom" textEncoding="utf-8" useDefaultWebProxy="true"> <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="67108864" maxBytesPerRead="4096" maxNameTableCharCount="67108864" /> <security mode="None"> <transport clientCredentialType="None" proxyCredentialType="None" realm="" /> <message clientCredentialType="UserName" algorithmSuite="Default" /> </security> </binding> <binding name="BaseLogicWSHTTP"> <security mode="None" /> </binding> <binding name="BaseLogicWSHTTPSec" /> </basicHttpBinding> </bindings> <behaviors> <serviceBehaviors> <behavior> <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment --> <serviceMetadata httpGetEnabled="true" /> <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information --> <serviceDebug includeExceptionDetailInFaults="true" /> </behavior> </serviceBehaviors> </behaviors> <serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" /> </system.serviceModel> I'm not sure if this affects the streaming function, because I'm using WCF4.0 rest template which config is dependent in Global.asax. One more thing is this, whether I run the service and passing a stream or not, the created file always contain this thing. How could I remove the "NUL" data? Thanks in advance. Edit public bool UploadFile(string filename, Stream fileStream) { try { FileStream fileToupload = new FileStream(filename, FileMode.Create); byte[] bytearray = new byte[10000]; int bytesRead, totalBytesRead = 0; do { bytesRead = fileStream.Read(bytearray, totalBytesRead, bytearray.Length - totalBytesRead); totalBytesRead += bytesRead; } while (bytesRead > 0); fileToupload.Write(bytearray, 0, totalBytesRead); fileToupload.Close(); fileToupload.Dispose(); } catch (Exception ex) { throw new Exception(ex.Message); } return true; }

    Read the article

  • generate unix timestamp from last time

    - by Nazmin
    hi guys, suppose i have one column in mysql database which is stated last time one equipment is up in h:i:s format (ex: 00:05:11) or 1d21h, means that the equipment is on since 5 min before, what is the best method i can convert this to unix timestamp, say if using php script how? or direct convert last unix timestamp using mysql function query. actually, i want to calculate for start time for this equipment uptime in unix timestamp where i have one column in mysql startcapture that will be deducted with last column to get start time. so starttime = startcapture - last (this last time that has to convert to unix timestamp based on now() - h:i:s ). but the problem is sometimes the format change from h:i:s to ex: 1d22h, if h:i:s means the equipment is up since ex: 00:05:11 min before and if 1d22h means the equipment already up 1 day 22 hours before. so the main things here is to convert last column to appropriate unix timestamp. please help guys, asap.

    Read the article

  • Solved::MessageQueue.BeginReceive() null ref error - c#

    - by ltech
    Have a windows service that listens to a msmq. In the OnStart method is have this protected override void OnStart(string[] args) { try { _queue = new MessageQueue(_qPath);//this part works as i had logging before and afer this call //Add MSMQ Event _queue.ReceiveCompleted += new ReceiveCompletedEventHandler(queue_ReceiveCompleted);//this part works as i had logging before and afer this call _queue.BeginReceive();//This is where it is failing - get a null reference exception } catch(Exception ex) { EventLogger.LogEvent(EventSource, EventLogType, "OnStart" + _lineFeed + ex.InnerException.ToString() + _lineFeed + ex.Message.ToString()); } } where private MessageQueue _queue = null; This works on my machine but when deployed to a windows 2003 server and running as Network service account, it fails Exception recvd: Service cannot be started. System.NullReferenceException: Object reference not set to an instance of an object. at MYService.Service.OnStart(String[] args) at System.ServiceProcess.ServiceBase.ServiceQueuedMainCallback(Object state) Solved: Turned out that the Q that i set up, I had to explicitly add Network Service account to it under security tab

    Read the article

  • unable to update gridview

    - by bhakti
    Please help ,i have added update/edit command button in gridview so to update data in my sql server database but am unable to do it. Data is not updated in database . ======code for onrowupdate======================================== protected void gRowUpdate(object sender, GridViewUpdateEventArgs e) { Books b = null; b = new Books(); DataTable dt=null; GridView g = (GridView)sender; try { dt=new DataTable(); b = new Books(); b.author = Convert.ToString(g.Rows[e.RowIndex].FindControl("Author")); b.bookID = Convert.ToInt32(g.Rows[e.RowIndex].FindControl("BookID")); b.title = Convert.ToString(g.Rows[e.RowIndex].FindControl("Title")); b.price = Convert.ToDouble(g.Rows[e.RowIndex].FindControl("Price")); // b.rec = Convert.ToString(g.Rows[e.RowIndex].FindControl("Date_of_reciept")); b.ed = Convert.ToString(g.Rows[e.RowIndex].FindControl("Edition")); b.bill = Convert.ToString(g.Rows[e.RowIndex].FindControl("Edition")); b.cre_by = Convert.ToString(g.Rows[e.RowIndex].FindControl("Edition")); b.src = Convert.ToString(g.Rows[e.RowIndex].FindControl("Edition")); b.pages = Convert.ToInt32(g.Rows[e.RowIndex].FindControl("Edition")); b.pub = Convert.ToString(g.Rows[e.RowIndex].FindControl("Edition")); b.mod_by = Convert.ToString(g.Rows[e.RowIndex].FindControl("Edition")); b.remark = Convert.ToString(g.Rows[e.RowIndex].FindControl("Edition")); // b.year = Convert.ToString(g.Rows[e.RowIndex].FindControl("Edition")); b.updatebook(b); g.EditIndex = -1; dt = b.GetAllBooks(); g.DataSource = dt; g.DataBind(); } catch (Exception ex) { throw (ex); } finally { b = null; } } ===================My stored procedure for update book able to update database by exec in sqlserver mgmt studio========================== set ANSI_NULLS ON set QUOTED_IDENTIFIER ON go ALTER PROCEDURE [dbo].[usp_updatebook] @bookid bigint, @author varchar(50), @title varchar(50), @price bigint, @src_equisition varchar(50), @bill_no varchar(50), @publisher varchar(50), @pages bigint, @remark varchar(50), @edition varchar(50), @created_by varchar(50), @modified_by varchar(50) /*@date_of_reciept datetime, @year_of_publication datetime*/ AS declare @modified_on datetime set @modified_on=getdate() UPDATE books SET author=@author, title=@title, price=@price, src_equisition=@src_equisition, bill_no=@bill_no, publisher=@publisher, /*Date_of_reciept=@date_of_reciept,*/ pages=@pages, remark=@remark, edition=@edition, /*Year_of_publication=@year_of_publication,*/ created_by=@created_by, modified_on=@modified_on, modified_by=@modified_by WHERE bookid=@bookid ========================class library function for update==================== public void updatebook(Books b) { DataAccess dbAccess = null; SqlCommand cmd = null; try { dbAccess = new DataAccess(); cmd = dbAccess.GetSQLCommand("usp_updatebook", CommandType.StoredProcedure); cmd.Parameters.Add("@bookid", SqlDbType.VarChar, 50).Value = b.bookID; cmd.Parameters.Add("@author", SqlDbType.VarChar, 50).Value = b.author; cmd.Parameters.Add("@title", SqlDbType.VarChar, 50).Value = b.title; cmd.Parameters.Add("@price", SqlDbType.Money).Value = b.price; cmd.Parameters.Add("@publisher", SqlDbType.VarChar, 50).Value = b.pub; // cmd.Parameters.Add("@year_of_publication", SqlDbType.DateTime).Value =Convert.ToDateTime( b.year); cmd.Parameters.Add("@src_equisition", SqlDbType.VarChar, 50).Value = b.src; cmd.Parameters.Add("@bill_no", SqlDbType.VarChar, 50).Value = b.bill; cmd.Parameters.Add("@remark", SqlDbType.VarChar, 50).Value = b.remark; cmd.Parameters.Add("@pages", SqlDbType.Int).Value = b.pages; cmd.Parameters.Add("@edition", SqlDbType.VarChar, 50).Value = b.ed; // cmd.Parameters.Add("@date_of_reciept", SqlDbType.DateTime).Value = Convert.ToDateTime(b.rec); // cmd.Parameters.Add("@created_on", SqlDbType.DateTime).Value = Convert.ToDateTime(b.cre_on); cmd.Parameters.Add("@created_by", SqlDbType.VarChar, 50).Value = b.cre_by; //cmd.Parameters.Add("@modified_on", SqlDbType.DateTime).Value = Convert.ToDateTime(b.mod_on); cmd.Parameters.Add("@modified_by", SqlDbType.VarChar, 50).Value = b.mod_by; cmd.ExecuteNonQuery(); } catch (Exception ex) { throw (ex); } finally { if (cmd.Connection != null && cmd.Connection.State == ConnectionState.Open) cmd.Connection.Close(); dbAccess = null; cmd = null; } } I have also tried to do update by following way protected void gv1_updating(object sender, GridViewUpdateEventArgs e) { GridView g = (GridView)sender; abc a = new abc(); DataTable dt = new DataTable(); try { a.cd_Id = Convert.ToInt32(g.DataKeys[e.RowIndex].Values[0].ToString()); //TextBox b = (TextBox)g.Rows[e.RowIndex].Cells[0].FindControl("cd_id"); TextBox c = (TextBox)g.Rows[e.RowIndex].Cells[2].FindControl("cd_name"); TextBox d = (TextBox)g.Rows[e.RowIndex].Cells[3].FindControl("version"); TextBox f = (TextBox)g.Rows[e.RowIndex].Cells[4].FindControl("company"); TextBox h = (TextBox)g.Rows[e.RowIndex].Cells[6].FindControl("created_by"); TextBox i = (TextBox)g.Rows[e.RowIndex].Cells[8].FindControl("modified_by"); //a.cd_Id = Convert.ToInt32(b.Text); a.cd_name = c.Text; a.ver = d.Text; a.comp = f.Text; a.cre_by = h.Text; a.mod_by = i.Text; a.updateDigi(a); g.EditIndex = -1; dt = a.GetAllDigi(); g.DataSource = dt; g.DataBind(); } catch(Exception ex) { throw (ex); } finally { dt = null; a = null; g = null; } } =================== but have error of Index out of range exception========= please do reply,thanxs in advance

    Read the article

  • Spring/Hibernate: InvocationTargetException when deleting entity

    - by niklassaers
    I'm sorry if this question is a bit vague, but I'm quite confused. I've got a controller that calls a service to delete an entity and then create an entity in its place. In the service, I've got my DAO, and my entity, and I want to delete my entity, so I call DAO.delete(entity); Then, seemingly out of nowhere, I get an InvocationTargetException. The parameters here are: method: public org.springframework.web.servlet.ModelAndView tld.myproject.view.web.controller.MyController.replaceEntity(org.springframework.web.multipart.MultipartFile,javax.servlet.http.HttpServletRequest) target: tld.myproject.view.web.controller.MyController@185918e args: [org.springframework.web.multipart.commons.CommonsMultipartFile@14812a6, org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest@c08a64] ex: java.lang.reflect.InvocationTargetException private Object doInvokeMethod(Method method, Object target, Object[] args) throws Exception { ReflectionUtils.makeAccessible(method); try { return method.invoke(target, args); } catch (InvocationTargetException ex) { ReflectionUtils.rethrowException(ex.getTargetException()); } throw new IllegalStateException("Should never get here"); } Does anyone have a suggestion to what's going on? Anything I can use in my debugging? Cheers Nik

    Read the article

  • AutoCompleteExtender positioning menu incorrectly when scrolled

    - by Colin
    We have an AutoCompleteExtender linked to a TextBox. Both controls are placed inside an UpdatePanel, and the UpdatePanel is displayed as a pop-up dialog using a Javascript library (Ext.BasicDialog). The pop-up is a div on the page, not a separate window. The problem is that when the user scrolls inside the pop-up, the AutoCompleteExtender shows its menu in the wrong place. It looks like it is taking the visible distance from the top of the popup and positioning the menu from the top of the inner html of the popup (which is not visible) We are using Version 1.0.20229.20821 of the AjaxControlToolkit, and we are targetting ASP.NET Framework vewrsion 2.0. I have tried to fix the menu by attaching the following Javascript to the OnClientShown event, but it pretty much does the same thing: function resetPosition(object, args) { var tb = object._element; // tb is the associated textbox. var offset = $('#' + tb.id).offset(); var ex = object._completionListElement; if (ex) { $('#' + ex.id).offset(offset); } }

    Read the article

  • asp.net Dynamic Data Site with custom own MetaData

    - by loviji
    Hello, I'm searching info about configuring own MetaData in asp.NET Dynamic Site. For example. I have a table in MS Sql Server with structure shown below: CREATE TABLE [dbo].[someTable]( [id] [int] NOT NULL, [pname] [nvarchar](20) NULL, [FullName] [nvarchar](50) NULL, [age] [int] NULL) and I there are 2 Ms Sql tables (I've created), sysTables and sysColumns. sysTables: ID sysTableName TableName TableDescription 1 | someTable |Persons |All Data about Persons in system sysColumns: ID TableName sysColumnName ColumnName ColumnDesc ColumnType MUnit 1 |someTable | sometable_pname| Name | Persona Name(ex. John)| nvarchar(20) | null 2 |someTable | sometable_Fullname| Full Name | Persona Name(ex. John Black)| nvarchar(50) | null 3 |someTable | sometable_age| age | Person age| int | null I want that, in Details/Edit/Insert/List/ListDetails pages use as MetaData sysColumns and sysTableData. Because, for ex. in DetailsPage fullName, it is not beatiful as Full Name . someIdea, is it possible? thanks

    Read the article

  • Linq query with subquery as comma-separated values

    - by Keith
    In my application, a company can have many employees and each employee may have have multiple email addresses. The database schema relates the tables like this: Company - CompanyEmployeeXref - Employee - EmployeeAddressXref - Email I am using Entity Framework and I want to create a LINQ query that returns the name of the company and a comma-separated list of it's employee's email addresses. Here is the query I am attempting: from c in Company join ex in CompanyEmployeeXref on c.Id equals ex.CompanyId join e in Employee on ex.EmployeeId equals e.Id join ax in EmployeeAddressXref on e.Id equals ax.EmployeeId join a in Address on ax.AddressId equals a.Id select new { c.Name, a.Email.Aggregate(x=x + ",") } Desired Output: "Company1", "[email protected],[email protected],[email protected]" "Company2", "[email protected],[email protected],[email protected]" ... I know this code is wrong, I think I'm missing a group by, but it illustrates the point. I'm not sure of the syntax. Is this even possible? Thanks for any help.

    Read the article

  • Using Regex to modify a String

    - by Christine Dehner
    I have a String that looks like this: Blah blah one.<tmp>[[url=b, link=c]]</tmp> Blah blah two. Also remember, blah blah three.<tmp>[[url=d, link=e]]</tmp> So I want to get b and d (the url attribute of tmp), and change the String so that it looks like this (the ex() function returns a String): Blah blah one.<tmp>[[url=b, link=c, add=ex(b)]]</tmp> Blah blah two. Also remember, blah blah three.<tmp>[[url=d, link=e, add=ex(d)]]</tmp> I need to use regex because no existing library parses this type of markup. I hope my explanation is clear. Thanks in advance!

    Read the article

  • How do I programmatically nullify a File Attachment in InfoPath Forms

    - by Doctor Zinda
    Howdy all, I'm running into a problem with some InfoPath C# code while trying to remove an attachment from a form. Basically the process is: User opens form User clicks button File attachment is cleared I've tried adding a blank attachment to my schema that never becomes populated, then setting the original field's value equal to that value by the method below. When debugging the form I catch an error: Schema validation found non-data type errors. Any tips here would be appreciated. public void BTN_ClearAttachment_Clicked(object sender, ClickedEventArgs e) { try { _OriginalAttachment.SetValue(_BLANK_ATTACHMENT.Value); } catch (Exception ex) { _ErrorField.SetValue(ex.Message + " : " + ex.StackTrace); } } Thanks, Dr Z Edit - P.S. I should clear up that both _OriginalAttachment & _ErrorField are both XPathNavigators, pointing at different schema elements. I've verified that these XPathNavigators are both pointing at valid schema elements.

    Read the article

  • What to log when an exception occurs?

    - by Rune
    public void EatDinner(string appetizer, string mainCourse, string dessert) { try { // Code } catch (Exception ex) { Logger.Log("Error in EatDinner", ex); return; } } When an exception occurs in a specific method, what should I be logging? I see a lot of the above in the code I work with. In these cases, I always have to talk to the person who experienced the error to find out what they were doing, step through the code, and try to reproduce the error. Is there any best practices or ways I can minimize all this extra work? Should I log the parameters in each method like this? Logger.Log("Params: " + appetizer + "," + mainCourse + "," + dessert, ex); Is there a better way to log the current environment? If I do it this way, will I need to write out all this stuff for each method I have in my application? Are there any best practices concerning scenarios like this?

    Read the article

  • C# Dynamic Keyword exception handling

    - by user972255
    The below code throws an exception when executing this line (i.e. something.Add(name)). I want to catch the actual exception when executing this. I mean I don't want to use catch(Exception ex) instead of that I want to know what is the correct exception thrown here. try { dynamic name= "test"; var something = new List<decimal>(); something.Add(name); } catch(Exception ex) { throw ex; } Thanks in advance.

    Read the article

  • Exit Try/Catch to prevent code after from being run

    - by coffeeaddict
    I've got for example a try/catch in my method: } catch (OurCustomExceptionObject1 ex) { txtErrorMessage.InnerHtml = "test 1"; } catch(OurCustomExceptionObject2 ex) { txtErrorMessage.InnerHtml = "test 2"; } catch (OurCustomExceptionObject3 ex) { txtErrorMessage.InnerHtml = "test 3"; } ... rest of code here is being executed after the try/catch I do not want the rest of code to run if any of the exceptions are caught. I'm handling the exceptions. I heard do not use Exit Try for some reason. Is that true, it's bad to do this? Is this the right way to halt execution of code thereafter the catch statement?

    Read the article

  • Confused by "let" in Clojure

    - by Tom Dalling
    I just started playing with Clojure, and I wrote a small script to help me understand some of the functions. It begins like this: (def *exprs-to-test* [ "(filter #(< % 3) '(1 2 3 4 3 2 1))" "(remove #(< % 3) '(1 2 3 4 3 2 1))" "(distinct '(1 2 3 4 3 2 1))" ]) Then it goes through *exprs-to-test*, evaluates them all, and prints the output like this: (doseq [exstr *exprs-to-test*] (do (println "===" (first (read-string exstr)) "=========================") (println "Code: " exstr) (println "Eval: " (eval (read-string exstr))) ) ) The above code is all working fine. However, (read-string exstr) is repeated so I tried to use let to eliminate the repetition like so: (doseq [exstr *exprs-to-test*] (let [ex (read-string exstr)] ( (do (println "===" (first ex) "=========================") (println "Code: " exstr) (println "Eval: " (eval ex)) ) )) ) But this works once for the first item in *exprs-to-test*, then crashes with a NullPointerException. Why is the addition of let causing the crash?

    Read the article

  • null reference exception was unhandled by user code

    - by user238319
    sir, i develop the following code in vs2005, now i just using this module in my new project @ vs 2008.. But this error was araised. I cant able to fix this problem... Private Sub DataAccess() Dim errHandle As New ErrorHandler Dim lobjCommon As New eCopsCommonFunctions Try AccessCodeDrplst.DataSource = CType(lobjCommon.gfuncGetAllEnrollmentSource(), DataSet) AccessCodeDrplst.DataValueField = "DataAccessCode" AccessCodeDrplst.DataTextField = "DataAccessDesc" AccessCodeDrplst.DataBind() 'lstEnrollmentSourceCode.DataValueField = "EnrollmentSourceCode" 'lstEnrollmentSourceCode.DataTextField = "EnrollmentSourceDesc" 'lstEnrollmentSourceCode.DataBind() '"Beneficiary Election" is pre selected as default value. By pals on Oct 24th 2007 'lstEnrollmentSourceCode.SelectedValue = "B" 'lstEnrollmentSourceCode.Items.Insert(0, New ListItem("Select", "0")) Catch ex As Exception errHandle.gProcHandleErrors(ex, Session("MemberID"), "SPStatus.aspx.vb, gprocFillSEPCode") Throw ex Finally lobjCommon = Nothing ///here the error occurs as 'NullException was unhandle by the user code' errHandle = Nothing End Try End Sub

    Read the article

  • How to close reconnect SocketIOClient on android?

    - by erginduran
    My problem is reconnect.I connect SocketIOClient.connect(..) in background service.I close service when internet connection is off.and I re-start service again connection on. How to close this reconnection?I don't want to reconnect SocketIOClient. Its my code: ConnectCallback mConnectCallback = new ConnectCallback() { @Override public void onConnectCompleted(Exception ex, SocketIOClient client) { if (ex != null) { ex.printStackTrace(); return; } client.setReconnectCallback(new ReconnectCallback() { @Override public void onReconnect() { // TODO Auto-generated method stub } }); client.setDisconnectCallback(new DisconnectCallback() { @Override public void onDisconnect(Exception arg0) { // TODO Auto-generated method stub } }); client.setErrorCallback(new ErrorCallback() { @Override public void onError(String arg0) { // TODO Auto-generated method stub } }); client.on("event", new EventCallback() { @Override public void onEvent(JSONArray jsonArray, Acknowledge acknowledge) { ///bla bla } }); ScreenChat.mClient = client; } };

    Read the article

  • SQL Query: Using IF statement in defining new field

    - by Tofig Hasanov
    I have a table with many fields and additionally several boolean fields (ex: BField1, BField2, BField3 etc.). I need to make a Select Query, which will select all fields except for boolean ones, and a new virtual field (ex: FirstTrueBool) whose value will equal to the name of the first TRUE Boolean Field. For ex: Say I have BField1 = False, BField2 = True, BField3 = true, BField4=false, in that case SQL Query should set [FirstTrueBool] to "BField2". Is that possible? Thank you in advance. P.S. I use Microsoft Access (MDB) Database and Jet Engine.

    Read the article

  • Regular Expression to get the size value of a CSS property?

    - by thiesdiggity
    I wrote a regular expression to get the size from a CSS property: /(([+-]?\d*\.?\d+(\s)*(px|em|ex|pt|in|pc|mm|cm)?)|thin|medium|thick)(\s|;|$)/i but for some reason its not working as intended. For example, when I run the following: preg_match_all('/(([+-]?\d*\.?\d+(\s)*(px|em|ex|pt|in|pc|mm|cm)?)|thin|medium|thick)(\s|;|$)/i', "border-bottom:1px solid #99999;", $matches); It outputs: 1px 99999; But I only want the 1px value returned. I understand why its returning the above but can't seem to figure out how to only return the size and not the color value. I tried using the following negative lookbehind but it's not working either: /(((?<!#\d{3}|#\d{6})[+-]?\d*\.?\d+(\s)*(px|em|ex|pt|in|pc|mm|cm)?)|thin|medium|thick)(\s|;|$)/i I want to use preg_match_all for those CSS properties that can have multiple size values (i.e. margin). Anyone have any ideas how to get this regex to return only the size values? Thanks for your help!

    Read the article

  • Easiest way to submit data via PHP?

    - by Abijah
    I'm new to PHP, and have spent 10 hours trying to figure this problem out. The goal is to take all data entered into this order form, and send it to my email via PHP. I have 2 questions: 1. I can get PHP to send data from a single menu item (example: Mexican Tortas), but how do I get PHP to send data from multiple items (example: Mexican Tortas, Fish Sandwich and Hamburger)? 2. How do I tell PHP to not send data from menu items that don't have the "How Many?" or "Customize It?" text fields filled out? If you could provide a super simple example (or a link to a learning resource) I would really appreciate it. Thank you, Abijah PHP <?php if(isset($_POST['submit'])) { $to = "[email protected]"; $subject = "New Order"; $name_field = $_POST['name']; $phone_field = $_POST['phone']; $item = $_POST['item']; $quantity = $_POST['quantity']; $customize = $_POST['customize']; } $body = "Name: $name_field\nPhone: $phone_field\n\nItem: $item\nQuantity: $quantity\nCustomize: $customize"; echo "Data has been submitted to $to!"; mail($to, $subject, $body); ?> HTML <form action="neworder.php" method="POST"> <div class ="item"> <img style="float:left; margin-right:15px; border:1px Solid #000; width:200px; height:155px;" src="images/mexicantortas.jpg"> <h1>Mexican Torta - $8.50</h1> <input name="item" type="hidden" value="Mexican Torta"/> <h2>How Many? <font color="#999999">Ex: 1, 2, 3...?</font></h2> <input name="quantity" type="text"/> <h3>Customize It? <font color="#999999">Ex: No Lettuce, Extra Cheese...</font></h3> <textarea name="customize"/></textarea> </div><!-- ITEM_LEFT --> <div class ="item"> <img style="float:left; margin-right:15px; border:1px Solid #000; width:200px; height:155px;" src="images/fishsandwich.jpg"> <h1>Fish Sandwich - $8.50</h1> <input name="item" type="hidden" value="Fish Sandwich"/> <h2>How Many? <font color="#999999">Ex: 1, 2, 3...?</font></h2> <input name="quantity" type="text"/> <h3>Customize It? <font color="#999999">Ex: No Lettuce, Extra Cheese...</font></h3> <textarea name="customize"/></textarea> </div><!-- ITEM_LEFT --> <div class ="item"> <img style="float:left; margin-right:15px; border:1px Solid #000; width:200px; height:155px;" src="images/hamburgers.jpg"> <h1>Hamburger w/ Fries - $7.00</h1> <input name="item" type="hidden" value="Fish Sandwich"/> <h2>How Many? <font color="#999999">Ex: 1, 2, 3...?</font></h2> <input name="quantity" type="text"/> <h3>Customize It? <font color="#999999">Ex: No Lettuce, Extra Cheese...</font></h3> <textarea name="customize"/></textarea> </div><!-- ITEM_LEFT --> <div class="horizontal_form"> <div class="form"> <h2>Place Your Order Now: <font size="3"><font color="#037B41">Fill in the form below, and we'll call you when your food is ready to be picked up...</font></font></h2> <p class="name"> <input type="text" name="name" id="name" style="text-align:center;" onClick="this.value='';" value="Enter your name"/> </p> <p class="phone"> <input type="text" name="phone" id="phone" style="text-align:center;" onClick="this.value='';" value="Enter your phone #"/> </p> <p class="submit"> <input type="submit" value="Place Order" name="submit"/> </p> </div><!-- FORM --> </div><!-- HORIZONTAL_FORM --> </form>

    Read the article

  • Whether to check for null

    - by coffeeaddict
    I know that you should always check incoming params to a method for null. But what if I have this scenario with a try/catch referring to a local variable. Do I really need to check for null below? Because it's gonna catch it anyway if it's null and the next line of code tries to use the refundResponse variable: public string DoRefund(...) { try { ...... string refundTransactionID = string.Empty; ...... RefundTransactionResponseType refundResponse = transaction.DoRefund(...); if (refundResponse != null) refundTransactionID = refundResponse.RefundTransactionID; ..... } catch (Exception ex) { LogError(ex); return ex.ToString(); } }

    Read the article

  • Catch a generic exception in Java?

    - by Alex Baranosky
    We use JUnit 3 at work and there is no ExpectedException annotation. I wanted to add a utility to our code to wrap this: try { someCode(); fail("some error message"); } catch (SomeSpecificExceptionType ex) { } So I tried this: public static class ExpectedExceptionUtility { public static <T extends Exception> void checkForExpectedException(String message, ExpectedExceptionBlock<T> block) { try { block.exceptionThrowingCode(); fail(message); } catch (T ex) { } } } However, Java cannot use generic exception types in a catch block, I think. How can I do something like this, working around the Java limitation? Is there a way to check that the ex variable is of type T?

    Read the article

  • trouble running smooth animation in thread only when using key listener

    - by heysuse renard
    first time using a forum for coding help so sorry if i post this all wrong. i have more than a few classes i don't think screenManger or core holds the problem but i included them just incase. i got most of this code working through a set of tutorials. but a certain point started trying to do more on my own. i want to play the animation only when i'm moving my sprite. in my KeyTest class i am using threads to run the animation it used to work (poorly) but now not at all pluss it really gunks up my computer. i think it's because of the thread. im new to threads so i'm not to sure if i should even be using one in this situation or if its dangerous for my computer. the animation worked smoothly when i had the sprite bouce around the screen forever. the animation loop played with out stopping. i think the main problem is between the animationThread, Sprite, and keyTest classes, but itcould be more indepth. if someone could point me in the right direction for making the animation run smoothly when i push down a key and stop runing when i let off it would be greatly apriciated. i already looked at this Java a moving animation (sprite) obviously we were doing the same tutorial. but i feel my problem is slightly different. p.s. sorry for the typos. import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; import java.util.ArrayList; import javax.swing.ImageIcon; import javax.swing.JFrame; public class KeyTest extends Core implements KeyListener { public static void main(String[] args) { new KeyTest().run(); } Sprite player1; Image hobo; Image background; animation hoboRun; animationThread t1; //init also calls init form superclass public void init() { super.init(); loadImages(); Window w = s.getFullScreenWindow(); w.setFocusTraversalKeysEnabled(false); w.addKeyListener(this); } //load method will go here. //load all pics need for animation and sprite public void loadImages() { background = new ImageIcon("\\\\STUART-PC\\Users\\Stuart\\workspace\\Gaming\\yellow square.jpg").getImage(); Image face1 = new ImageIcon("\\\\STUART-PC\\Users\\Stuart\\workspace\\Gaming\\circle.png").getImage(); Image face2 = new ImageIcon("\\\\STUART-PC\\Users\\Stuart\\workspace\\Gaming\\one eye.png").getImage(); hoboRun = new animation(); hoboRun.addScene(face1, 250); hoboRun.addScene(face2, 250); player1 = new Sprite(hoboRun); this.t1 = new animationThread(); this.t1.setAnimation(player1); } //key pressed public void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode(); if (keyCode == KeyEvent.VK_ESCAPE) { stop(); } if (keyCode == KeyEvent.VK_RIGHT) { player1.setVelocityX(0.3f); try { this.t1.setRunning(true); Thread th1 = new Thread(this.t1); th1.start(); } catch (Exception ex) { System.out.println("noooo"); } } if (keyCode == KeyEvent.VK_LEFT) { player1.setVelocityX(-0.3f); try { this.t1.setRunning(true); Thread th1 = new Thread(this.t1); th1.start(); } catch (Exception ex) { System.out.println("noooo"); } } if (keyCode == KeyEvent.VK_DOWN) { player1.setVelocityY(0.3f); try { this.t1.setRunning(true); Thread th1 = new Thread(this.t1); th1.start(); } catch (Exception ex) { System.out.println("noooo"); } } if (keyCode == KeyEvent.VK_UP) { player1.setVelocityY(-0.3f); try { this.t1.setRunning(true); Thread th1 = new Thread(this.t1);; th1.start(); } catch (Exception ex) { System.out.println("noooo"); } } else { e.consume(); } } //keyReleased @SuppressWarnings("static-access") public void keyReleased(KeyEvent e) { int keyCode = e.getKeyCode(); if (keyCode == KeyEvent.VK_RIGHT || keyCode == KeyEvent.VK_LEFT) { player1.setVelocityX(0); try { this.t1.setRunning(false); } catch (Exception ex) { } } if (keyCode == KeyEvent.VK_UP || keyCode == KeyEvent.VK_DOWN) { player1.setVelocityY(0); try { this.t1.setRunning(false); } catch (Exception ex) { } } else { e.consume(); } } //last method from interface public void keyTyped(KeyEvent e) { e.consume(); } //draw public void draw(Graphics2D g) { Window w = s.getFullScreenWindow(); g.setColor(w.getBackground()); g.fillRect(0, 0, s.getWidth(), s.getHieght()); g.setColor(w.getForeground()); g.drawImage(player1.getImage(), Math.round(player1.getX()), Math.round(player1.getY()), null); } public void update(long timePassed) { player1.update(timePassed); } } abstract class Core { private static DisplayMode modes[] = { new DisplayMode(1600, 900, 64, 0), new DisplayMode(800, 600, 32, 0), new DisplayMode(800, 600, 24, 0), new DisplayMode(800, 600, 16, 0), new DisplayMode(800, 480, 32, 0), new DisplayMode(800, 480, 24, 0), new DisplayMode(800, 480, 16, 0),}; private boolean running; protected ScreenManager s; //stop method public void stop() { running = false; } public void run() { try { init(); gameLoop(); } finally { s.restoreScreen(); } } //set to full screen //set current background here public void init() { s = new ScreenManager(); DisplayMode dm = s.findFirstCompatibleMode(modes); s.setFullScreen(dm); Window w = s.getFullScreenWindow(); w.setFont(new Font("Arial", Font.PLAIN, 20)); w.setBackground(Color.GREEN); w.setForeground(Color.WHITE); running = true; } //main gameLoop public void gameLoop() { long startTime = System.currentTimeMillis(); long cumTime = startTime; while (running) { long timePassed = System.currentTimeMillis() - cumTime; cumTime += timePassed; update(timePassed); Graphics2D g = s.getGraphics(); draw(g); g.dispose(); s.update(); try { Thread.sleep(20); } catch (Exception ex) { } } } //update animation public void update(long timePassed) { } //draws to screen abstract void draw(Graphics2D g); } class animationThread implements Runnable { String name; boolean playing; Sprite a; //constructor takes input from keyboard public animationThread() { } //The run method for animation public void run() { long startTime = System.currentTimeMillis(); long cumTime = startTime; boolean test = getRunning(); while (test) { long timePassed = System.currentTimeMillis() - cumTime; cumTime += timePassed; test = getRunning(); } } public String getName() { return name; } public void setAnimation(Sprite a) { this.a = a; } public void setName(String name) { this.name = name; } public void setRunning(boolean running) { this.playing = running; } public boolean getRunning() { return playing; } } class animation { private ArrayList scenes; private int sceneIndex; private long movieTime; private long totalTime; //constructor public animation() { scenes = new ArrayList(); totalTime = 0; start(); } //add scene to ArrayLisy and set time for each scene public synchronized void addScene(Image i, long t) { totalTime += t; scenes.add(new OneScene(i, totalTime)); } public synchronized void start() { movieTime = 0; sceneIndex = 0; } //change scenes public synchronized void update(long timePassed) { if (scenes.size() > 1) { movieTime += timePassed; if (movieTime >= totalTime) { movieTime = 0; sceneIndex = 0; } while (movieTime > getScene(sceneIndex).endTime) { sceneIndex++; } } } //get animations current scene(aka image) public synchronized Image getImage() { if (scenes.size() == 0) { return null; } else { return getScene(sceneIndex).pic; } } //get scene private OneScene getScene(int x) { return (OneScene) scenes.get(x); } //Private Inner CLASS////////////// private class OneScene { Image pic; long endTime; public OneScene(Image pic, long endTime) { this.pic = pic; this.endTime = endTime; } } } class Sprite { private animation a; private float x; private float y; private float vx; private float vy; //Constructor public Sprite(animation a) { this.a = a; } //change position public void update(long timePassed) { x += vx * timePassed; y += vy * timePassed; } public void startAnimation(long timePassed) { a.update(timePassed); } //get x position public float getX() { return x; } //get y position public float getY() { return y; } //set x public void setX(float x) { this.x = x; } //set y public void setY(float y) { this.y = y; } //get sprite width public int getWidth() { return a.getImage().getWidth(null); } //get sprite height public int getHeight() { return a.getImage().getHeight(null); } //get horizontal velocity public float getVelocityX() { return vx; } //get vertical velocity public float getVelocityY() { return vx; } //set horizontal velocity public void setVelocityX(float vx) { this.vx = vx; } //set vertical velocity public void setVelocityY(float vy) { this.vy = vy; } //get sprite / image public Image getImage() { return a.getImage(); } } class ScreenManager { private GraphicsDevice vc; public ScreenManager() { GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment(); vc = e.getDefaultScreenDevice(); } //get all compatible DM public DisplayMode[] getCompatibleDisplayModes() { return vc.getDisplayModes(); } //compares DM passed into vc DM and see if they match public DisplayMode findFirstCompatibleMode(DisplayMode modes[]) { DisplayMode goodModes[] = vc.getDisplayModes(); for (int x = 0; x < modes.length; x++) { for (int y = 0; y < goodModes.length; y++) { if (displayModesMatch(modes[x], goodModes[y])) { return modes[x]; } } } return null; } //get current DM public DisplayMode getCurrentDisplayMode() { return vc.getDisplayMode(); } //checks if two modes match each other public boolean displayModesMatch(DisplayMode m1, DisplayMode m2) { if (m1.getWidth() != m2.getWidth() || m1.getHeight() != m2.getHeight()) { return false; } if (m1.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && m2.getBitDepth() != DisplayMode.BIT_DEPTH_MULTI && m1.getBitDepth() != m2.getBitDepth()) { return false; } if (m1.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && m2.getRefreshRate() != DisplayMode.REFRESH_RATE_UNKNOWN && m1.getRefreshRate() != m2.getRefreshRate()) { return false; } return true; } //make frame full screen public void setFullScreen(DisplayMode dm) { JFrame f = new JFrame(); f.setUndecorated(true); f.setIgnoreRepaint(true); f.setResizable(false); vc.setFullScreenWindow(f); if (dm != null && vc.isDisplayChangeSupported()) { try { vc.setDisplayMode(dm); } catch (Exception ex) { } } f.createBufferStrategy(2); } //sets graphics object = this return public Graphics2D getGraphics() { Window w = vc.getFullScreenWindow(); if (w != null) { BufferStrategy s = w.getBufferStrategy(); return (Graphics2D) s.getDrawGraphics(); } else { return null; } } //updates display public void update() { Window w = vc.getFullScreenWindow(); if (w != null) { BufferStrategy s = w.getBufferStrategy(); if (!s.contentsLost()) { s.show(); } } } //returns full screen window public Window getFullScreenWindow() { return vc.getFullScreenWindow(); } //get width of window public int getWidth() { Window w = vc.getFullScreenWindow(); if (w != null) { return w.getWidth(); } else { return 0; } } //get height of window public int getHieght() { Window w = vc.getFullScreenWindow(); if (w != null) { return w.getHeight(); } else { return 0; } } //get out of full screen public void restoreScreen() { Window w = vc.getFullScreenWindow(); if (w != null) { w.dispose(); } vc.setFullScreenWindow(null); } //create image compatible with monitor public BufferedImage createCopatibleImage(int w, int h, int t) { Window win = vc.getFullScreenWindow(); if (win != null) { GraphicsConfiguration gc = win.getGraphicsConfiguration(); return gc.createCompatibleImage(w, h, t); } return null; } }

    Read the article

  • SmtpClient and Locked File Attachments

    - by Rick Strahl
    Got a note a couple of days ago from a client using one of my generic routines that wraps SmtpClient. Apparently whenever a file has been attached to a message and emailed with SmtpClient the file remains locked after the message has been sent. Oddly this particular issue hasn’t cropped up before for me although these routines are in use in a number of applications I’ve built. The wrapper I use was built mainly to backfit an old pre-.NET 2.0 email client I built using Sockets to avoid the CDO nightmares of the .NET 1.x mail client. The current class retained the same class interface but now internally uses SmtpClient which holds a flat property interface that makes it less verbose to send off email messages. File attachments in this interface are handled by providing a comma delimited list for files in an Attachments string property which is then collected along with the other flat property settings and eventually passed on to SmtpClient in the form of a MailMessage structure. The jist of the code is something like this: /// <summary> /// Fully self contained mail sending method. Sends an email message by connecting /// and disconnecting from the email server. /// </summary> /// <returns>true or false</returns> public bool SendMail() { if (!this.Connect()) return false; try { // Create and configure the message MailMessage msg = this.GetMessage(); smtp.Send(msg); this.OnSendComplete(this); } catch (Exception ex) { string msg = ex.Message; if (ex.InnerException != null) msg = ex.InnerException.Message; this.SetError(msg); this.OnSendError(this); return false; } finally { // close connection and clear out headers // SmtpClient instance nulled out this.Close(); } return true; } /// <summary> /// Configures the message interface /// </summary> /// <param name="msg"></param> protected virtual MailMessage GetMessage() { MailMessage msg = new MailMessage(); msg.Body = this.Message; msg.Subject = this.Subject; msg.From = new MailAddress(this.SenderEmail, this.SenderName); if (!string.IsNullOrEmpty(this.ReplyTo)) msg.ReplyTo = new MailAddress(this.ReplyTo); // Send all the different recipients this.AssignMailAddresses(msg.To, this.Recipient); this.AssignMailAddresses(msg.CC, this.CC); this.AssignMailAddresses(msg.Bcc, this.BCC); if (!string.IsNullOrEmpty(this.Attachments)) { string[] files = this.Attachments.Split(new char[2] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (string file in files) { msg.Attachments.Add(new Attachment(file)); } } if (this.ContentType.StartsWith("text/html")) msg.IsBodyHtml = true; else msg.IsBodyHtml = false; msg.BodyEncoding = this.Encoding; … additional code omitted return msg; } Basically this code collects all the property settings of the wrapper object and applies them to the SmtpClient and in GetMessage() to an individual MailMessage properties. Specifically notice that attachment filenames are converted from a comma-delimited string to filenames from which new attachments are created. The code as it’s written however, will cause the problem with file attachments not being released properly. Internally .NET opens up stream handles and reads the files from disk to dump them into the email send stream. The attachments are always sent correctly but the local files are not immediately closed. As you probably guessed the issue is simply that some resources are not automatcially disposed when sending is complete and sure enough the following code change fixes the problem: // Create and configure the message using (MailMessage msg = this.GetMessage()) { smtp.Send(msg); if (this.SendComplete != null) this.OnSendComplete(this); // or use an explicit msg.Dispose() here } The Message object requires an explicit call to Dispose() (or a using() block as I have here) to force the attachment files to get closed. I think this is rather odd behavior for this scenario however. The code I use passes in filenames and my expectation of an API that accepts file names is that it uses the files by opening and streaming them and then closing them when done. Why keep the streams open and require an explicit .Dispose() by the calling code which is bound to lead to unexpected behavior just as my customer ran into? Any API level code should clean up as much as possible and this is clearly not happening here resulting in unexpected behavior. Apparently lots of other folks have run into this before as I found based on a few Twitter comments on this topic. Odd to me too is that SmtpClient() doesn’t implement IDisposable – it’s only the MailMessage (and Attachments) that implement it and require it to clean up for left over resources like open file handles. This means that you couldn’t even use a using() statement around the SmtpClient code to resolve this – instead you’d have to wrap it around the message object which again is rather unexpected. Well, chalk that one up to another small unexpected behavior that wasted a half an hour of my time – hopefully this post will help someone avoid this same half an hour of hunting and searching. Resources: Full code to SmptClientNative (West Wind Web Toolkit Repository) SmtpClient Documentation MSDN © Rick Strahl, West Wind Technologies, 2005-2010Posted in .NET  

    Read the article

  • Searching for the last logon of users in Active Directory

    - by Robert May
    I needed to clean out a bunch of old accounts at Veracity Solutions, and wanted to delete those that hadn’t used their account in more than a year. I found that AD has a property on objects called the lastLogonTimestamp.  However, this value isn’t exposed to you in any useful fashion.  Sure, you can pull up ADSI Edit and and eventually get to it there, but it’s painful. I spent some time searching, and discovered that there’s not much out there to help, so I thought a blog post showing exactly how to get at this information would be in order. Basically, what you end up doing is using System.DirectoryServices to search for accounts and then filtering those for users, doing some conversion and such to make it happen.  Basically, the end result of this is that you get a list of users with their logon information and you can then do with that what you will.  I turned my list into an observable collection and bound it into a XAML form. One important note, you need to add a reference to ActiveDs Type Library in the COM section of the world in references to get to LargeInteger. Here’s the class: namespace Veracity.Utilities { using System; using System.Collections.Generic; using System.DirectoryServices; using ActiveDs; using log4net; /// <summary> /// Finds users inside of the active directory system. /// </summary> public class UserFinder { /// <summary> /// Creates the default logger /// </summary> private static readonly ILog log = LogManager.GetLogger(typeof(UserFinder)); /// <summary> /// Finds last logon information /// </summary> /// <param name="domain">The domain to search.</param> /// <param name="userName">The username for the query.</param> /// <param name="password">The password for the query.</param> /// <returns>A list of users with their last logon information.</returns> public IList<UserLoginInformation> GetLastLogonInformation(string domain, string userName, string password) { IList<UserLoginInformation> result = new List<UserLoginInformation>(); DirectoryEntry entry = new DirectoryEntry(domain, userName, password, AuthenticationTypes.Secure); DirectorySearcher directorySearcher = new DirectorySearcher(entry); directorySearcher.PropertyNamesOnly = true; directorySearcher.PropertiesToLoad.Add("name"); directorySearcher.PropertiesToLoad.Add("lastLogonTimeStamp"); SearchResultCollection searchResults; try { searchResults = directorySearcher.FindAll(); } catch (System.Exception ex) { log.Error("Failed to do a find all.", ex); throw; } try { foreach (SearchResult searchResult in searchResults) { DirectoryEntry resultEntry = searchResult.GetDirectoryEntry(); if (resultEntry.SchemaClassName == "user") { UserLoginInformation logon = new UserLoginInformation(); logon.Name = resultEntry.Name; PropertyValueCollection timeStampObject = resultEntry.Properties["lastLogonTimeStamp"]; if (timeStampObject.Count > 0) { IADsLargeInteger logonTimeStamp = (IADsLargeInteger)timeStampObject[0]; long lastLogon = (long)((uint)logonTimeStamp.LowPart + (((long)logonTimeStamp.HighPart) << 32)); logon.LastLogonTime = DateTime.FromFileTime(lastLogon); } result.Add(logon); } } } catch (System.Exception ex) { log.Error("Failed to iterate search results.", ex); throw; } return result; } } } Some important things to note: Username and Password can be set to null and if your computer us part of the domain, this may still work. Domain should be set to something like LDAP://servername/CN=Users,CN=Domain,CN=com You’re actually getting a com object back, so that’s why the LongInteger conversions are happening.  The class for UserLoginInformation looks like this:   namespace Veracity.Utilities { using System; /// <summary> /// Represents user login information. /// </summary> public class UserLoginInformation { /// <summary> /// Gets or sets Name /// </summary> public string Name { get; set; } /// <summary> /// Gets or sets LastLogonTime /// </summary> public DateTime LastLogonTime { get; set; } /// <summary> /// Gets the age of the account. /// </summary> public TimeSpan AccountAge { get { TimeSpan result = TimeSpan.Zero; if (this.LastLogonTime != DateTime.MinValue) { result = DateTime.Now.Subtract(this.LastLogonTime); } return result; } } } } I hope this is useful and instructive. Technorati Tags: Active Directory

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16 17 18  | Next Page >