Search Results

Search found 7140 results on 286 pages for 'mike tostring'.

Page 8/286 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • Regular expression help

    - by DJPB
    I there I'm working on a C# app, and I get a string with a date or part of a date and i need to take day, month and year for that string ex: string example='31-12-2010' string day = Regex.Match(example, "REGULAR EXPRESSION FOR DAY").ToString(); string month = Regex.Match(example, "REGULAR EXPRESSION FOR MONTH").ToString() string year = Regex.Match(example, "REGULAR EXPRESSION FOR YEAR").ToString() day = "31" month = "12" year = "2010" ex2: string example='12-2010' string month = Regex.Match(example, "REGULAR EXPRESSION FOR MONTH").ToString() string year = Regex.Match(example, "REGULAR EXPRESSION FOR YEAR").ToString() month = "12" year = "2010" any idea? tks

    Read the article

  • A better javascript to string function?

    - by Jeff
    Before I go and create this myself, I thought I'd see if anyone knows a library that does this. I'm looking for a function that will take something in Javascript, be it an array, an associative array, a number, or even a string, and convert it to something that looks like it. For example: toString([1,2,3]) === '[1, 2, 3]' toString([[1,2], [2,4], [3,6]]) === '[[1,2], [2,4], [3,6]]' toString(23) === '23' toString('hello world') === 'hello world' toString({'one': 1, 'two': 2, 'three': 3}) === "{'one': 1, 'two': 2, 'three': 3}"

    Read the article

  • How to pad number with leading zero with C#

    - by Jalpesh P. Vadgama
    Recently I was working with a project where I was in need to format a number in such a way which can apply leading zero for particular format.  So after doing such R and D I have found a great way to apply this leading zero format. I was having need that I need to pad number in 5 digit format. So following is a table in which format I need my leading zero format. 1-> 00001 20->00020 300->00300 4000->04000 50000->5000 So in the above example you can see that 1 will become 00001 and 20 will become 00200 format so on. So to display an integer value in decimal format I have applied interger.Tostring(String) method where I have passed “Dn” as the value of the format parameter, where n represents the minimum length of the string. So if we pass 5 it will have padding up to 5 digits. So let’s create a simple console application and see how its works. Following is a code for that. using System; namespace LeadingZero { class Program { static void Main(string[] args) { int a = 1; int b = 20; int c = 300; int d = 4000; int e = 50000; Console.WriteLine(string.Format("{0}------>{1}",a,a.ToString("D5"))); Console.WriteLine(string.Format("{0}------>{1}", b, b.ToString("D5"))); Console.WriteLine(string.Format("{0}------>{1}", c, c.ToString("D5"))); Console.WriteLine(string.Format("{0}------>{1}", d, d.ToString("D5"))); Console.WriteLine(string.Format("{0}------>{1}", e, e.ToString("D5"))); Console.ReadKey(); } } } As you can see in the above code I have use string.Format function to display value of integer and after using integer value’s  ToString method. Now Let’s run the console application and following is the output as expected. Here you can see the integer number are converted into the exact output that we requires. That’s it you can see it’s very easy. We have written code in nice clean way and without writing any extra code or loop. Hope you liked it. Stay tuned for more.. Till than happy programming.

    Read the article

  • How to display strings in activity 3 from activity 1, 2? [migrated]

    - by user107160
    I need to get strings values from two different activities say activity1 and activity2, each activity should have maximum 4 edittext field..so totally eight fields should be displayed orderly in activity3. I have tried the code which is not displaying in the activity3. Look at code, Activity1 String namef = fname.getText().toString(); Intent first = new Intent(AssessmentActivity.this, Second.class); first.putExtra("list1", namef); startActivity(first); String namel = lname.getText().toString(); Intent second = new Intent(AssessmentActivity.this, Second.class); second.putExtra("list2", namel); startActivity(second); String phone = mob.getText().toString(); Intent third = new Intent(AssessmentActivity.this, Second.class); third.putExtra("list3", phone); startActivity(third); String mailid = email.getText().toString(); Intent fourth = new Intent(AssessmentActivity.this, Second.class); fourth.putExtra("list4", mailid); startActivity(fourth); Activity2 String cont = addr.getText().toString(); Intent fifth = new Intent(Second.this, Third.class); fifth.putExtra("list5", cont); startActivity(fifth); String db = dob.getText().toString(); Intent sixth = new Intent(Second.this, Third.class); sixth.putExtra("list6", db); startActivity(sixth); String nation = citizen.getText().toString(); Intent Seventh = new Intent(Second.this, Third.class); Seventh.putExtra("list7", nation); startActivity(Seventh); String subject = course.getText().toString(); Intent Eight = new Intent(Second.this, Third.class); Eight.putExtra("list8", subject); startActivity(Eight); *Activity3* TextView first = (TextView)findViewById(R.id.textView2); String fieldone = getIntent().getStringExtra("list1" ); first.setText(fieldone); TextView second = (TextView)findViewById(R.id.textView3); String fieldtwo = getIntent().getStringExtra("list2" ); second.setText(fieldtwo); TextView third = (TextView)findViewById(R.id.textView4); String fieldthree = getIntent().getStringExtra("list3" ); third.setText(fieldthree); TextView fourth = (TextView)findViewById(R.id.textView5); String fieldfour = getIntent().getStringExtra("list4" ); fourth.setText(fieldfour); TextView fifth = (TextView)findViewById(R.id.textView6); String fieldfive = getIntent().getStringExtra("list5" ); fifth.setText(fieldfive); TextView sixth = (TextView)findViewById(R.id.textView7); String fieldsix = getIntent().getStringExtra("list6" ); sixth.setText(fieldsix); TextView seventh = (TextView)findViewById(R.id.textView8); String fieldseven = getIntent().getStringExtra("list7" ); seventh.setText(fieldseven); TextView eight = (TextView)findViewById(R.id.textView3); String fieldeight = getIntent().getStringExtra("list8"); eight.setText(fieldeight);

    Read the article

  • Calling AuditQuerySystemPolicy() (advapi32.dll) from C# returns "The parameter is incorrect"

    - by JCCyC
    The sequence is like follows: Open a policy handle with LsaOpenPolicy() (not shown) Call LsaQueryInformationPolicy() to get the number of categories; For each category: Call AuditLookupCategoryGuidFromCategoryId() to turn the enum value into a GUID; Call AuditEnumerateSubCategories() to get a list of the GUIDs of all subcategories; Call AuditQuerySystemPolicy() to get the audit policies for the subcategories. All of these work and return expected, sensible values except the last. Calling AuditQuerySystemPolicy() gets me a "The parameter is incorrect" error. I'm thinking there must be some subtle unmarshaling problem. I'm probably misinterpreting what exactly AuditEnumerateSubCategories() returns, but I'm stumped. You'll see (commented) I tried to dereference the return pointer from AuditEnumerateSubCategories() as a pointer. Doing or not doing that gives the same result. Code: #region LSA types public enum POLICY_INFORMATION_CLASS { PolicyAuditLogInformation = 1, PolicyAuditEventsInformation, PolicyPrimaryDomainInformation, PolicyPdAccountInformation, PolicyAccountDomainInformation, PolicyLsaServerRoleInformation, PolicyReplicaSourceInformation, PolicyDefaultQuotaInformation, PolicyModificationInformation, PolicyAuditFullSetInformation, PolicyAuditFullQueryInformation, PolicyDnsDomainInformation } public enum POLICY_AUDIT_EVENT_TYPE { AuditCategorySystem, AuditCategoryLogon, AuditCategoryObjectAccess, AuditCategoryPrivilegeUse, AuditCategoryDetailedTracking, AuditCategoryPolicyChange, AuditCategoryAccountManagement, AuditCategoryDirectoryServiceAccess, AuditCategoryAccountLogon } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct POLICY_AUDIT_EVENTS_INFO { public bool AuditingMode; public IntPtr EventAuditingOptions; public UInt32 MaximumAuditEventCount; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct GUID { public UInt32 Data1; public UInt16 Data2; public UInt16 Data3; public Byte Data4a; public Byte Data4b; public Byte Data4c; public Byte Data4d; public Byte Data4e; public Byte Data4f; public Byte Data4g; public Byte Data4h; public override string ToString() { return Data1.ToString("x8") + "-" + Data2.ToString("x4") + "-" + Data3.ToString("x4") + "-" + Data4a.ToString("x2") + Data4b.ToString("x2") + "-" + Data4c.ToString("x2") + Data4d.ToString("x2") + Data4e.ToString("x2") + Data4f.ToString("x2") + Data4g.ToString("x2") + Data4h.ToString("x2"); } } #endregion #region LSA Imports [DllImport("kernel32.dll")] extern static int GetLastError(); [DllImport("advapi32.dll", CharSet = CharSet.Unicode, PreserveSig = true)] public static extern UInt32 LsaNtStatusToWinError( long Status); [DllImport("advapi32.dll", CharSet = CharSet.Unicode, PreserveSig = true)] public static extern long LsaOpenPolicy( ref LSA_UNICODE_STRING SystemName, ref LSA_OBJECT_ATTRIBUTES ObjectAttributes, Int32 DesiredAccess, out IntPtr PolicyHandle ); [DllImport("advapi32.dll", CharSet = CharSet.Unicode, PreserveSig = true)] public static extern long LsaClose(IntPtr PolicyHandle); [DllImport("advapi32.dll", CharSet = CharSet.Unicode, PreserveSig = true)] public static extern long LsaFreeMemory(IntPtr Buffer); [DllImport("advapi32.dll", CharSet = CharSet.Unicode, PreserveSig = true)] public static extern void AuditFree(IntPtr Buffer); [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)] public static extern long LsaQueryInformationPolicy( IntPtr PolicyHandle, POLICY_INFORMATION_CLASS InformationClass, out IntPtr Buffer); [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)] public static extern bool AuditLookupCategoryGuidFromCategoryId( POLICY_AUDIT_EVENT_TYPE AuditCategoryId, IntPtr pAuditCategoryGuid); [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)] public static extern bool AuditEnumerateSubCategories( IntPtr pAuditCategoryGuid, bool bRetrieveAllSubCategories, out IntPtr ppAuditSubCategoriesArray, out ulong pCountReturned); [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)] public static extern bool AuditQuerySystemPolicy( IntPtr pSubCategoryGuids, ulong PolicyCount, out IntPtr ppAuditPolicy); #endregion Dictionary<string, UInt32> retList = new Dictionary<string, UInt32>(); long lretVal; uint retVal; IntPtr pAuditEventsInfo; lretVal = LsaQueryInformationPolicy(policyHandle, POLICY_INFORMATION_CLASS.PolicyAuditEventsInformation, out pAuditEventsInfo); retVal = LsaNtStatusToWinError(lretVal); if (retVal != 0) { LsaClose(policyHandle); throw new System.ComponentModel.Win32Exception((int)retVal); } POLICY_AUDIT_EVENTS_INFO myAuditEventsInfo = new POLICY_AUDIT_EVENTS_INFO(); myAuditEventsInfo = (POLICY_AUDIT_EVENTS_INFO)Marshal.PtrToStructure(pAuditEventsInfo, myAuditEventsInfo.GetType()); IntPtr subCats = IntPtr.Zero; ulong nSubCats = 0; for (int audCat = 0; audCat < myAuditEventsInfo.MaximumAuditEventCount; audCat++) { GUID audCatGuid = new GUID(); if (!AuditLookupCategoryGuidFromCategoryId((POLICY_AUDIT_EVENT_TYPE)audCat, new IntPtr(&audCatGuid))) { int causingError = GetLastError(); LsaFreeMemory(pAuditEventsInfo); LsaClose(policyHandle); throw new System.ComponentModel.Win32Exception(causingError); } if (!AuditEnumerateSubCategories(new IntPtr(&audCatGuid), true, out subCats, out nSubCats)) { int causingError = GetLastError(); LsaFreeMemory(pAuditEventsInfo); LsaClose(policyHandle); throw new System.ComponentModel.Win32Exception(causingError); } // Dereference the first pointer-to-pointer to point to the first subcategory // subCats = (IntPtr)Marshal.PtrToStructure(subCats, subCats.GetType()); if (nSubCats > 0) { IntPtr audPolicies = IntPtr.Zero; if (!AuditQuerySystemPolicy(subCats, nSubCats, out audPolicies)) { int causingError = GetLastError(); if (subCats != IntPtr.Zero) AuditFree(subCats); LsaFreeMemory(pAuditEventsInfo); LsaClose(policyHandle); throw new System.ComponentModel.Win32Exception(causingError); } AUDIT_POLICY_INFORMATION myAudPol = new AUDIT_POLICY_INFORMATION(); for (ulong audSubCat = 0; audSubCat < nSubCats; audSubCat++) { // Process audPolicies[audSubCat], turn GUIDs into names, fill retList. // http://msdn.microsoft.com/en-us/library/aa373931%28VS.85%29.aspx // http://msdn.microsoft.com/en-us/library/bb648638%28VS.85%29.aspx IntPtr itemAddr = IntPtr.Zero; IntPtr itemAddrAddr = new IntPtr(audPolicies.ToInt64() + (long)(audSubCat * (ulong)Marshal.SizeOf(itemAddr))); itemAddr = (IntPtr)Marshal.PtrToStructure(itemAddrAddr, itemAddr.GetType()); myAudPol = (AUDIT_POLICY_INFORMATION)Marshal.PtrToStructure(itemAddr, myAudPol.GetType()); retList[myAudPol.AuditSubCategoryGuid.ToString()] = myAudPol.AuditingInformation; } if (audPolicies != IntPtr.Zero) AuditFree(audPolicies); } if (subCats != IntPtr.Zero) AuditFree(subCats); subCats = IntPtr.Zero; nSubCats = 0; } lretVal = LsaFreeMemory(pAuditEventsInfo); retVal = LsaNtStatusToWinError(lretVal); if (retVal != 0) throw new System.ComponentModel.Win32Exception((int)retVal); lretVal = LsaClose(policyHandle); retVal = LsaNtStatusToWinError(lretVal); if (retVal != 0) throw new System.ComponentModel.Win32Exception((int)retVal);

    Read the article

  • How can i optimize this c# code?

    - by Pandiya Chendur
    I have converted my Datatable to json string use the following method... public string GetJSONString(DataTable Dt) { string[] StrDc = new string[Dt.Columns.Count]; string HeadStr = string.Empty; for (int i = 0; i < Dt.Columns.Count; i++) { StrDc[i] = Dt.Columns[i].Caption; HeadStr += "\"" + StrDc[i] + "\" : \"" + StrDc[i] + i.ToString() + "¾" + "\","; } HeadStr = HeadStr.Substring(0, HeadStr.Length - 1); StringBuilder Sb = new StringBuilder(); Sb.Append("{\"" + Dt.TableName + "\" : ["); for (int i = 0; i < Dt.Rows.Count; i++) { string TempStr = HeadStr; Sb.Append("{"); for (int j = 0; j < Dt.Columns.Count; j++) { if (Dt.Rows[i][j].ToString().Contains("'") == true) { Dt.Rows[i][j] = Dt.Rows[i][j].ToString().Replace("'", ""); } TempStr = TempStr.Replace(Dt.Columns[j] + j.ToString() + "¾", Dt.Rows[i][j].ToString()); } Sb.Append(TempStr + "},"); } Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1)); Sb.Append("]}"); return Sb.ToString(); } Is this fair enough or still there is margin for optimization to make it execute faster.... Any suggestion...

    Read the article

  • Getting Service Tag from Dell Machine using .net?

    - by JonH
    Hello folks I've got a class that pulls model information (hardware info) for a local machine code is like so: Imports System.Management Public Class clsWMI Private objOS As ManagementObjectSearcher Private objCS As ManagementObjectSearcher Private objMgmt As ManagementObject Private m_strComputerName As String Private m_strManufacturer As String Private m_StrModel As String Private m_strOSName As String Private m_strOSVersion As String Private m_strSystemType As String Private m_strTPM As String Private m_strWindowsDir As String Public Sub New() objOS = New ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem") objCS = New ManagementObjectSearcher("SELECT * FROM Win32_ComputerSystem") For Each objMgmt In objOS.Get m_strOSName = objMgmt("name").ToString() m_strOSVersion = objMgmt("version").ToString() m_strComputerName = objMgmt("csname").ToString() m_strWindowsDir = objMgmt("windowsdirectory").ToString() Next For Each objMgmt In objCS.Get m_strManufacturer = objMgmt("manufacturer").ToString() m_StrModel = objMgmt("model").ToString() m_strSystemType = objMgmt("systemtype").ToString m_strTPM = objMgmt("totalphysicalmemory").ToString() Next End Sub Public ReadOnly Property ComputerName() Get ComputerName = m_strComputerName End Get End Property Public ReadOnly Property Manufacturer() Get Manufacturer = m_strManufacturer End Get End Property Public ReadOnly Property Model() Get Model = m_StrModel End Get End Property Public ReadOnly Property OsName() Get OsName = m_strOSName End Get End Property Public ReadOnly Property OSVersion() Get OSVersion = m_strOSVersion End Get End Property Public ReadOnly Property SystemType() Get SystemType = m_strSystemType End Get End Property Public ReadOnly Property TotalPhysicalMemory() Get TotalPhysicalMemory = m_strTPM End Get End Property Public ReadOnly Property WindowsDirectory() Get WindowsDirectory = m_strWindowsDir End Get End Property End Class Any possibility to get a service tag from WMI ? From the client side form I display values like so: Dim objWMI As New clsWMI() With objWMI Debug.WriteLine("Computer Name = " & .ComputerName) Me.Label1.Text = "Name: " & .ComputerName Debug.WriteLine("Computer Manufacturer = " & .Manufacturer) Me.Label2.Text = "Manufacturer: " & .Manufacturer Debug.WriteLine("Computer Model = " & .Model) Me.Label3.Text = "Model: " & .Model Debug.WriteLine("OS Name = " & .OsName) Me.Label4.Text = "OS Name: " & .OsName Debug.WriteLine("OS Version = " & .OSVersion) Me.Label5.Text = "OS VERSION: " & .OSVersion Debug.WriteLine("System Type = " & .SystemType) Me.Label6.Text = "System type = " & .SystemType Debug.WriteLine("Total Physical Memory = " & .TotalPhysicalMemory) Me.Label7.Text = "Memory: " & .TotalPhysicalMemory Debug.WriteLine("Windows Directory = " & .WindowsDirectory) Me.Label8.Text = "Win Directory: " & .WindowsDirectory End With

    Read the article

  • How to Display a Bmp in a RTF control in VB.net

    - by Gerolkae
    I Started with this C# Question I'm trying to Display a bmp image inside a rtf Box for a Bot program I'm making. This function is supposed to convert a bitmap to rtf code whis is inserted to another rtf formatter srtring with additional text. Kind of like Smilies being used in a chat program. For some reason the output of this function gets rejected by the RTF Box and Vanishes completly. I'm not sure if it the way I'm converting the bmp to a Binary string or if its tied in with the header tags 'returns the RTF string representation of our picture Public Shared Function PictureToRTF(ByVal Bmp As Bitmap) As String Dim stream As New MemoryStream() Bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp) Dim bytes As Byte() = stream.ToArray() Dim str As String = BitConverter.ToString(bytes, 0).Replace("-", String.Empty) 'header to string we want to insert Using g As Graphics = Main.CreateGraphics() xDpi = g.DpiX yDpi = g.DpiY End Using Dim _rtf As New StringBuilder() ' Calculate the current width of the image in (0.01)mm Dim picw As Integer = CInt(Math.Round((Bmp.Width / xDpi) * HMM_PER_INCH)) ' Calculate the current height of the image in (0.01)mm Dim pich As Integer = CInt(Math.Round((Bmp.Height / yDpi) * HMM_PER_INCH)) ' Calculate the target width of the image in twips Dim picwgoal As Integer = CInt(Math.Round((Bmp.Width / xDpi) * TWIPS_PER_INCH)) ' Calculate the target height of the image in twips Dim pichgoal As Integer = CInt(Math.Round((Bmp.Height / yDpi) * TWIPS_PER_INCH)) ' Append values to RTF string _rtf.Append("{\pict\wbitmap0") _rtf.Append("\picw") _rtf.Append(Bmp.Width.ToString) ' _rtf.Append(picw.ToString) _rtf.Append("\pich") _rtf.Append(Bmp.Height.ToString) ' _rtf.Append(pich.ToString) _rtf.Append("\wbmbitspixel24\wbmplanes1") _rtf.Append("\wbmwidthbytes40") _rtf.Append("\picwgoal") _rtf.Append(picwgoal.ToString) _rtf.Append("\pichgoal") _rtf.Append(pichgoal.ToString) _rtf.Append("\bin ") _rtf.Append(str.ToLower & "}") Return _rtf.ToString End Function

    Read the article

  • Dynamic Table CheckBoxes not having a "Checked" true value

    - by LuvlyOvipositor
    I have been working on a web app using ASP.NET with the code base as C#. I have a dynamic table that resizes based on a return from a SQL query; with a check box added in the third cell of each row. The checkbox is assigned an ID according to an index and the date. When users hit the submit button, the code is supposed to get a value from each row that is checked. However, when looping through the rows, none of the check boxes ever have a value of true for the Checked property. The ID persists, but the value of the checkbox seems to be lost. Code for adding the Checkboxes: cell = new TableCell(); CheckBox cb = new CheckBox(); cell.ApplyStyle(TS); cb.ID = index.ToString() + " " + lstDate.SelectedItem.Text.ToString(); if (reader["RestartStatus"].ToString() == "0") { cb.Checked = false; cb.Enabled = true; } else { cb.Checked = true; } cell.Controls.Add(cb); The code for getting the checkbox value: for (int i = 0; i < CompTable.Rows.Count; i++) { int t3 = CompTable.Rows[i].Cells[2].Controls.Count; Control temp = null; if (t3 0) { temp = CompTable.Rows[i].Cells[2].Controls[0]; } string t2 = i.ToString() + " " + lstDate.SelectedItem.Text.ToString(); if ( temp != null && ((CheckBox)temp).ID == i.ToString() + " " + lstDate.SelectedItem.Text.ToString()) { //Separated into 2 if statements for debugging purposes //ID is correct, but .Checked is always false (even if all of the boxes are checked) if (((CheckBox)temp).Checked == true) { tlist.Add(CompTable.Rows[i].Cells[0].Text.ToString()); } } }

    Read the article

  • How to perform Linq select new with datetime in SQL 2008

    - by kd7iwp
    In our C# code I recently changed a line from inside a linq-to-sql select new query as follows: OrderDate = (p.OrderDate.HasValue ? p.OrderDate.Value.Year.ToString() + "-" + p.OrderDate.Value.Month.ToString() + "-" + p.OrderDate.Value.Day.ToString() : "") To: OrderDate = (p.OrderDate.HasValue ? p.OrderDate.Value.ToString("yyyy-mm-dd") : "") The change makes the line smaller and cleaner. It also works fine with our SQL 2008 database in our development environment. However, when the code deployed to our production environment which uses SQL 2005 I received an exception stating: Nullable Type must have a value. For further analysis I copied (p.OrderDate.HasValue ? p.OrderDate.Value.ToString("yyyy-mm-dd") : "") into a string (outside of a Linq statement) and had no problems at all, so it only causes an in issue inside my Linq. Is this problem just something to do with SQL 2005 using different date formats than from SQL 2008? Here's more of the Linq: dt = FilteredOrders.Where(x => x != null).Select(p => new { Order = p.OrderId, link = "/order/" + p.OrderId.ToString(), StudentId = (p.PersonId.HasValue ? p.PersonId.Value : 0), FirstName = p.IdentifierAccount.Person.FirstName, LastName = p.IdentifierAccount.Person.LastName, DeliverBy = p.DeliverBy, OrderDate = p.OrderDate.HasValue ? p.OrderDate.Value.Date.ToString("yyyy-mm-dd") : ""}).ToDataTable(); This is selecting from a List of Order objects. The FilteredOrders list is from another linq-to-sql query and I call .AsEnumerable on it before giving it to this particular select new query. Doing this in regular code works fine: if (o.OrderDate.HasValue) tempString += " " + o.OrderDate.Value.Date.ToString("yyyy-mm-dd");

    Read the article

  • unexplained spacing in horizontal panel in GWT

    - by special0ne
    hi, i am adding widgets to a horizontal panel, and i want them to be all once next to the other on the left corner. even though i have set the spacing=0 and alignment= left the widgets still have space between them. they are spread evenly in the panel. please see the code here for the widget C'tor and the function that adds a new tab (toggle button) tabsPanel is a horizontalPanel, that you can see is aligned to left/right according to the locale any advise would be appreciated thanks.... public TabsWidgetManager(int width, int height, int tabs_shift_direction){ DecoratorPanel decorContent = new DecoratorPanel(); DecoratorPanel decorTitle = new DecoratorPanel(); widgetPanel.setSize(Integer.toString(width), Integer.toString(height)); tabsPanel.setSize(Integer.toString(UIConst.USER_CONTENT_WIDTH), Integer.toString(UIConst.TW_DEFAULT_TAB_HEIGHT)); tabsPanel.setSpacing(0); if (tabs_shift_direction==1) tabsPanel.setHorizontalAlignment(HorizontalPanel.ALIGN_LEFT); else tabsPanel.setHorizontalAlignment(HorizontalPanel.ALIGN_RIGHT); decorTitle.add(tabsPanel); contentPanel.setSize(Integer.toString(UIConst.USER_CONTENT_WIDTH), Integer.toString(UIConst.USER_CONTENT_MINUS_TABS_HEIGHT)); decorContent.add(contentPanel); widgetPanel.add(decorTitle, 0, 0); widgetPanel.add(decorContent, 0, UIConst.TW_DEFAULT_TAB_HEIGHT+15); initWidget(widgetPanel); } public void addTab(String title, Widget widget){ widget.setVisible(false); ToggleButton tab = new ToggleButton(title); tabsList.add(tab); tab.setSize(Integer.toString(UIConst.TW_TAB_DEFAULT_WIDTH), Integer.toString(UIConst.TW_TAB_DEFAULT_HEIGHT)); tab.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { handleTabClick((ToggleButton)event.getSource()); } }); //adding to the map tabToWidget.put(tab, widget); // adding to the tabs bar tabsPanel.add(tab); //adding to the content contentPanel.add(widget); }

    Read the article

  • How to get the value of an XML element using Linq even when empty.

    - by Yeodave
    Please excuse my stupidity, I tend to find the traversing XML overly complicated. I am using ASP.NET in VB. I have an XML document which contains all the details of staff in my company... <staff> <staffName>Test Staff</staffName> <staffTitle>Slave</staffTitle> <staffDepartmentName>Finance</staffDepartmentName> <staffOffice>London</staffOffice> <staffEmail>[email protected]</staffEmail> <staffPhone>0207 123 456</staffPhone> <staffNotes>Working hours Mon to Thurs 9.15 - 5.15</staffNotes> <staffBio></staffBio> </staff> As you can see, some nodes do not always contain data for ever member of staff; only Directors have biographies. I access the values like this... For Each staff In ( _ From matches In myXMLFile.Descendants("staff").Descendants("staffName") _ Where matches.Nodes(0).ToString.ToLower.Contains(LCase(search)) _ Order By matches.Value _ Select matches) staffName = staff.Descendants("staffName").Nodes(0).ToString) staffTitle = staff.Descendants("staffTitle").Nodes(0).ToString) staffOffice = staff.Descendants("staffOffice").Nodes(0).ToString) staffEmail = staff.Descendants("staffEmail").Nodes(0).ToString) staffPhone = staff.Descendants("staffPhone").Nodes(0).ToString) staffNotes = staff.Descendants("staffNotes").Nodes(0).ToString) staffBio = staff.Descendants("staffBio").Nodes(0).ToString) ' Do something with that data... Next Once it gets to staffBio I get an error saying "Object reference not set to an instance of an object." obviously because that node does not exist. My question is how can I assign the value to a variable even when it is empty without having to do a conditional check before each assignment?

    Read the article

  • VB.Net: exception on ExecuteReader() using OleDbCommand and Access

    - by Shane Fagan
    Hi again all, im getting the error below for this SQL statement in VB.Net 'Fill in the datagrid with the info needed from the accdb file 'to make it simple to access the db connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data " connstring += "Source=" & Application.StartupPath & "\AuctioneerSystem.accdb" 'make the new connection conn = New System.Data.OleDb.OleDbConnection(connstring) 'the sql command SQLString = "SELECT AllPropertyDetails.PropertyID, Street, Town, County, Acres, Quotas, ResidenceDetails, Status, HighestBid, AskingPrice FROM AllPropertyDetails " SQLString += "INNER JOIN Land ON AllPropertyDetails.PropertyID = Land.PropertyID " SQLString += "WHERE Deleted = False " If PriceRadioButton.Checked = True Then SQLString += "ORDER BY AskingPrice ASC" ElseIf AcresRadioButton.Checked = True Then SQLString += "ORDER BY Acres ASC" End If 'try to open the connection conn.Open() 'if the connection is open If ConnectionState.Open.ToString = "Open" Then 'use the sqlstring and conn to create the command cmd = New System.Data.OleDb.OleDbCommand(SQLString, conn) 'read the db and put it into dr dr = cmd.ExecuteReader If dr.HasRows Then 'if there is rows in the db then make sure the list box is clear 'clear the rows and columns if there is rows in the data grid LandDataGridView.Rows.Clear() LandDataGridView.Columns.Clear() 'add the columns LandDataGridView.Columns.Add("PropertyNumber", "Property Number") LandDataGridView.Columns.Add("Address", "Address") LandDataGridView.Columns.Add("Acres", "No. of Acres") LandDataGridView.Columns.Add("Quotas", "Quotas") LandDataGridView.Columns.Add("Details", "Residence Details") LandDataGridView.Columns.Add("Status", "Status") LandDataGridView.Columns.Add("HighestBid", "Highest Bid") LandDataGridView.Columns.Add("Price", "Asking Price") While dr.Read 'output the fields into the data grid LandDataGridView.Rows.Add( _ dr.Item("PropertyID").ToString _ , dr.Item("Street").ToString & " " & dr.Item("Town").ToString & ", " & dr.Item("County").ToString _ , dr.Item("Acres").ToString _ , dr.Item("Quota").ToString _ , dr.Item("ResidenceDetails").ToString _ , dr.Item("Status").ToString _ , dr.Item("HighestBid").ToString _ , dr.Item("AskingPrice").ToString) End While End If 'close the data reader dr.Close() End If 'close the connection conn.Close() Any ideas why its not working? The fields in the DB and the table names seem ok but its not working :/ The tables are AllPropertyDetails ProperyID:Number Street: text Town: text County: text Status: text HighestBid: Currency AskingPrice: Currency Land PropertyID: Number Acres: Number Quotas: Text ResidenceDetails: text System.InvalidOperationException was unhandled Message="An error occurred creating the form. See Exception.InnerException for details. The error is: No value given for one or more required parameters." Source="AuctioneerProject" StackTrace: at AuctioneerProject.My.MyProject.MyForms.Create__Instance__[T](T Instance) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 190 at AuctioneerProject.My.MyProject.MyForms.get_LandReport() at AuctioneerProject.ReportsMenu.LandButton_Click(Object sender, EventArgs e) in C:\Users\admin\Desktop\Auctioneers\AuctioneerProject\AuctioneerProject\ReportsMenu.vb:line 4 at System.Windows.Forms.Control.OnClick(EventArgs e) at System.Windows.Forms.Button.OnClick(EventArgs e) at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ButtonBase.WndProc(Message& m) at System.Windows.Forms.Button.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.Run(ApplicationContext context) at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun() at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel() at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine) at AuctioneerProject.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81 at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() InnerException: System.Data.OleDb.OleDbException ErrorCode=-2147217904 Message="No value given for one or more required parameters." Source="Microsoft Office Access Database Engine" StackTrace: at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr) at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method) at System.Data.OleDb.OleDbCommand.ExecuteReader(CommandBehavior behavior) at System.Data.OleDb.OleDbCommand.ExecuteReader() at AuctioneerProject.LandReport.load_Land() in C:\Users\admin\Desktop\Auctioneers\AuctioneerProject\AuctioneerProject\LandReport.vb:line 37 at AuctioneerProject.LandReport.PriceRadioButton_CheckedChanged(Object sender, EventArgs e) in C:\Users\admin\Desktop\Auctioneers\AuctioneerProject\AuctioneerProject\LandReport.vb:line 79 at System.Windows.Forms.RadioButton.OnCheckedChanged(EventArgs e) at System.Windows.Forms.RadioButton.set_Checked(Boolean value) at AuctioneerProject.LandReport.InitializeComponent() in C:\Users\admin\Desktop\Auctioneers\AuctioneerProject\AuctioneerProject\LandReport.designer.vb:line 40 at AuctioneerProject.LandReport..ctor() in C:\Users\admin\Desktop\Auctioneers\AuctioneerProject\AuctioneerProject\LandReport.vb:line 5 InnerException:

    Read the article

  • How to create a dynamically built Context Menu clickEvent

    - by Chris
    C#, winform I have a DataGridView and a context menu that opens when you right click a specific column. What shows up in the context menu is dependant on what's in the field clicked on - paths to multiple files (the paths are manipulated to create a full UNC path to the correct file). The only problem is that I can't get the click working. I did not drag and drop the context menu from the toolbar, I created it programmically. I figured that if I can get the path (let's call it ContextMenuChosen) to show up in MessageBox.Show(ContextMenuChosen); I could set the same to System.Diagnostics.Process.Start(ContextMenuChosen); The Mydgv_MouseUp event below actually works to the point where I can get it to fire off MessageBox.Show("foo!"); when something in the context menu is selected but that's where it ends. I left in a bunch of comments below showing what I've tried when it one of the paths are clicked. Some result in empty strings, others error (Object not set to an instance...). I searched code all day yesterday but couldn't find another way to hook up a dynamically built Context Menu clickEvent. Code and comments: ContextMenu m = new ContextMenu(); // SHOW THE RIGHT CLICK MENU private void Mydgv_MouseClick(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) { int currentMouseOverCol = Mydgv.HitTest(e.X, e.Y).ColumnIndex; int currentMouseOverRow = Mydgv.HitTest(e.X, e.Y).RowIndex; if (currentMouseOverRow >= 0 && currentMouseOverCol == 6) { string[] paths = myPaths.Split(';'); foreach (string path in paths) { string UNCPath = "\\\\1.1.1.1\\c$\\MyPath\\"; string FilePath = path.Replace("c:\\MyPath\\", @""); m.MenuItems.Add(new MenuItem(UNCPath + FilePath)); } } m.Show(Mydgv, new Point(e.X, e.Y)); } } // SELECTING SOMETHING IN THE RIGHT CLICK MENU private void Mydgv_MouseUp(object sender, MouseEventArgs e) { DataGridView.HitTestInfo hitTestInfo; if (e.Button == MouseButtons.Right) { hitTestInfo = Mydgv.HitTest(e.X, e.Y); // If column is first column if (hitTestInfo.Type == DataGridViewHitTestType.Cell && hitTestInfo.ColumnIndex == 6) { //MessageBox.Show(m.ToString()); ////MessageBox.Show(m.Tag.ToString()); //MessageBox.Show(m.Name.ToString()); //MessageBox.Show(m.MenuItems.ToString()); ////MessageBox.Show(m.MdiListItem.ToString()); // MessageBox.Show(m.Name); //if (m.MenuItems.Count > 0) //MessageBox.Show(m.MdiListItem.Text); //MessageBox.Show(m.ToString()); //MessageBox.Show(m.MenuItems.ToString()); //Mydgv.ContextMenu.Show(m.Name.ToString()); //MessageBox.Show(ContextMenu.ToString()); //MessageBox.Show(ContextMenu.MenuItems.ToString()); //MenuItem.text //MessageBox.Show(this.ContextMenu.MenuItems.ToString()); } m.MenuItems.Clear(); } } I'm very close to completing this so any help would be much appreciated. Thanks, ~ Chris

    Read the article

  • Innovative SPARC: Lighting a Fire Under Oracle's New Hardware Business

    - by Paulo Folgado
    "There's a certain level of things you can do with commercially available parts," says Oracle Executive Vice President Mike Splain. But, he notes, you can do so much more if you design the parts yourself. Mike Splain,EVP, OracleYou can, for example, design cryptographic accelerators into your microprocessors so customers can run their networks fully encrypted if they choose.Of course, it helps if you've already built multiple processing "cores" into those chips so they can handle all that encrypting and decrypting while still getting their other work done.System on a ChipAs the leader of Oracle Microelectronics, Mike knows how implementing clever innovations in silicon can give systems a real competitive advantage.The SPARC microprocessors that his team designed at Sun pioneered the concept of multiple cores several years ago, and the UltraSPARC T2 processor--the industry's first "system on a chip"--packs up to eight cores per chip, each running as many as eight threads at once. That's the most cores and threads of any general-purpose processor. Looking back, Mike points out that the real value of large enterprise-class servers was their ability to run a lot of very large applications in parallel."The beauty of our CMT [chip multi-threading] machines is you can get that same kind of parallel-processing capability at a much lower cost and in a much smaller footprint," he says.The Whole StackWhat has Mike excited these days is that suddenly the opportunity to innovate is much bigger as part of Oracle."In my group, we used to look up the software stack and say, 'We can do any innovation we want, provided the only thing we have to change is what's in the Solaris operating system'--or maybe Java," he says. "If we wanted to change things beyond that, we'd have to go outside the walls of Sun and we'd have to convince the vendors: 'You have to align with us, you have to test with us, you have to build for us, and then you'll reap the benefits.' Now we get access to the entire stack. We can look all the way through the stack and say, 'Okay, what would make the database go faster? What would make the middleware go faster?'"Changing the WorldMike and his microelectronics team also like the fact that Oracle is not just any software company. We're #1 in database, middleware, business intelligence, and more."We're like all the other engineers from Sun; we believe we can change the world, if we can just figure out how to get people to pay attention to us," he says. "Now there's a mechanism at Oracle--much more so than we ever had at Sun."He notes, too, that every innovation in SPARC has involved some combination of hardware and softwareoptimization."Take our cryptography framework, for example. Sure, we can accelerate rapidly, but the Solaris OS has to provide the right set of interfaces that applications can tap into," Mike says. "Same thing with our multicore architecture. We have to have software that can utilize all those threads and run in parallel." His engineers, he points out, have never been interested in producing chips that sell as mere components."Our chips are always designed to go into systems and be combined with various pieces of software," he says. "Our job is to enable the creation of systems."

    Read the article

  • Silverlight Cream for February 13, 2011 -- #1046

    - by Dave Campbell
    In this Issue: Loek van den Ouweland, Colin Eberhardt, Rudi Grobler, Joost van Schaik, Mike Taulty(-2-, -3-), Deborah Kurata, David Kelley, Peter Foot, Samuel Jack(-2-), and WindowsPhoneGeek(-2-). Above the Fold: Silverlight: "Silverlight Simple MVVM Commanding" Deborah Kurata WP7: "WP7 CustomInputPrompt control with Cancel button" WindowsPhoneGeek Expression Blend: "Silverlight Templated Image Button with two images" Loek van den Ouweland Shoutouts: Dave Campbell posted a write-up about the project he's on and the use of Sterling: Sterling Object-Oriented Database for ISO 1.0 Released!... Also see Jeremy Likness' post on the 1.0 release: Sterling Object-Oriented Database 1.0 RTM Not necessarily Silverlight, but darn cool, a great control by Sasha Barber: WPF : A Weird 3d based control snoutholder announced new content: Windows Phone 7 QuickStarts Live! From SilverlightCream.com: Silverlight Templated Image Button with two images Loek van den Ouweland has a video tutorial up for creating an ImageButton with a hover state... Expression Blend coolness, and check out the external links he has to their training site. Windows Phone 7 Performance Measurements – Emulator vs. Hardware Colin Eberhardt's latest is a popular post comparing performance metrics between the WP7 emulator and a real device. Mileage may vary, but I'm pretty sure the overall results are conculsive, and should help the way you view your app as you're building in the emulator. WP7: WebClient vs HttpWebRequest Rudi Grobler's latest is a discussion of WebClient and HttpWebRequest, gives coding examples of each plus discussion of why you may choose one over the other... and pay attention to his comment about mobile providers. A Blendable Windows Phone 7 / Silverlight clipping behavior Joost van Schaik posted this WP7/Silverlight clipping behavior he developed because all the other solutions were not blendable. Another really useful piece of code from Joost! Blend Bits 22–Being Stylish Mike Taulty has 3 more episodes in his Blend Bits series... first up is on one Styles... explicit, implicit, inheriting... you name it, he's covering it! Blend Bits 23–Templating Part 1 MIke Taulty then has the beginning of a series within his Blend Bits series on Templating. This is something you just have to either bite the bullet and go with Blend to do, or consume someone else's work. Mike shows us how to do it ourself by tweaking the visual aspects of a checkbox Blend Bits 24–Templating Part 2 In part 2 of the Templating series, Mike Taulty digs deeper into Blend and cracks open the Listbox control to take a bunch of the inner elements out for a spin... fun stuff and great tutorial, Mike! Silverlight Simple MVVM Commanding Deborah Kurata has another great MVVM post up... if you don't have your head wrapped around commanding yet, this is a good place to start that process... VB and C# as always. App Development for Windows Phone 7 101 David Kelley goes through the basics of producing a WP7 app both from the Silverlight and XNA side... good info and good external links to get you going. Copyable TextBlock for Windows Phone Peter Foot takes a look at the Copy/Paste functionality in WP7 and how to apply it to a TextBlock... which is NOT an out-of-the-box solution. How to deploy to, and debug, multiple instances of the Windows Phone 7 emulator Samuel Jack has a couple posts up this week... first is this clever one on running multiple copies of the emulator at once... too cool for debugging a multi-player game! Multi-player enabling my Windows Phone 7 game: Day 3 – The Server Side Samuel Jack's latest is a detailed look at his day 3 adventure of taking his multi-player game to WP7... lots of information and external links... what do you say, give him another day? :) WP7 CustomInputPrompt control with Cancel button WindowsPhoneGeek has a couple more posts up... first is this "CustomInputPrompt" control based off the InputPrompt from Coding4Fun. Implementing Windows Phone 7 DataTemplateSelector and CustomDataTemplateSelector In his latest post, WindowsPhoneGeek writes a DataTemplateSelector to allow different data templates for different list elements based on the type of the element. Stay in the 'Light! Twitter SilverlightNews | Twitter WynApse | WynApse.com | Tagged Posts | SilverlightCream Join me @ SilverlightCream | Phoenix Silverlight User Group Technorati Tags: Silverlight    Silverlight 3    Silverlight 4    Windows Phone MIX10

    Read the article

  • Include weather information in ASP.Net site from weather.com services

    - by sreejukg
    In this article, I am going to demonstrate how you can use the XMLOAP services (referred as XOAP from here onwards) provided by weather.com to display the weather information in your website. The XOAP services are available to be used for free of charge, provided you are comply with requirements from weather.com. I am writing this article from a technical point of view. If you are planning to use weather.com XOAP services in your application, please refer to the terms and conditions from weather.com website. In order to start using the XOAP services, you need to sign up the XOAP datafeed. The signing process is simple, you simply browse the url http://www.weather.com/services/xmloap.html. The URL looks similar to the following. Click on the sign up button, you will reach the registration page. Here you need to specify the site name you need to use this feed for. The form looks similar to the following. Once you fill all the mandatory information, click on save and continue button. That’s it. The registration is over. You will receive an email that contains your partner id, license key and SDK. The SDK available in a zipped format, contains the terms of use and documentation about the services available. Other than this the SDK includes the logos and icons required to display the weather information. As per the SDK, currently there are 2 types of information available through XOAP. These services are Current Conditions for over 30,000 U.S. and over 7,900 international Location IDs Updated at least Hourly Five-Day Forecast (today + 4 additional forecast days in consecutive order beginning with tomorrow) for over 30,000 U.S. and over 7,900 international Location IDs Updated at least Three Times Daily The SDK provides detailed information about the fields included in response of each service. Additionally there is a refresh rate that you need to comply with. As per the SDK, the refresh rate means the following “Refresh Rate” shall mean the maximum frequency with which you may call the XML Feed for a given LocID requesting a data set for that LocID. During the time period in between refresh periods the data must be cached by you either in the memory on your servers or in Your Desktop Application. About the Services Weather.com will provide you with access to the XML Feed over the Internet through the hostname xoap.weather.com. The weather data from the XML feed must be requested for a specific location. So you need a location ID (LOC ID). The XML feed work with 2 types of location IDs. First one is with City Identifiers and second one is using 5 Digit US postal codes. If you do not know your location ID, don’t worry, there is a location id search service available for you to retrieve the location id from city name. Since I am a resident in the Kingdom of Bahrain, I am going to retrieve the weather information for Manama(the capital of Bahrain) . In order to get the location ID for Manama, type the following URL in your address bar. http://xoap.weather.com/search/search?where=manama I got the following XML output. <?xml version="1.0" encoding="UTF-8"?> <!-- This document is intended only for use by authorized licensees of The –> <!-- Weather Channel. Unauthorized use is prohibited. Copyright 1995-2011, –> <!-- The Weather Channel Interactive, Inc. All Rights Reserved. –> <search ver="3.0">       <loc id="BAXX0001" type="1">Al Manama, Bahrain</loc> </search> You can try this with any city name, if the city is available, it will return the location id, and otherwise, it will return nothing. In order to get the weather information, from XOAP,  you need to pass certain parameters to the XOAP service. A brief about the parameters are as follows. Please refer SDK for more details. Parameter name Possible Value cc Optional, if you include this, the current condition will be returned. Value can be anything, as it will be ignored e.g. cc=* dayf If you want the forecast for 5 days, specify dayf=5 This is optional iink Value should be XOAP par Your partner id. You can find this in your registration email from weather.com prod Value should be XOAP key The license key assigned to you. This will be available in the registration email unit s or m (standard or matric or you can think of Celsius/Fahrenheit) this is optional field, if not specified the unit will be standard(s) The URL host for the XOAP service is http://xoap.weather.com. So for my purpose, I need the following request to be made to access the XOAP services. http://xoap.weather.com/weather/local/BAXX0001?cc=*&link=xoap&prod=xoap&par=*********&key=************** (The ***** to be replaced with the corresponding alternatives) The response XML have a root element “weather”. Under the root element, it has the following sections <head> - the meta data information about the weather results returned. <loc> - the location data block that provides, the information about the location for which the wheather data is retrieved. <lnks> - the 4 promotional links you need to place along with the weather display. Additional to these 4 links, there should be another link with weather channel logo to the home page of weather.com. <cc> - the current condition data. This element will be there only if you specify the cc element in the request. <dayf> - the forcast data as you specified. This element will be there only if you specify the dayf in the request. In this walkthrough, I am going to capture the weather information for Manama (Location ID: BAXX0001). You need 2 applications to display weather information in your website. A Console application that retrieves data from the XMLOAP and store in the SQL Server database (or any data store as you prefer).This application will be scheduled to execute in every 25 minutes using windows task scheduler, so that we can comply with the refresh rate. A web application that display data from the SQL Server database Retrieve the Weather from XOAP I have created a console application named, Weather Service. I created a SQL server database, with the following columns. I named the table as tblweather. You are free to choose any name. Column name Description lastUpdated Datetime, this is the last time when the weather data is updated. This is the time of the service running TemparatureDateTime The date and time returned by XML feed Temparature The temperature returned by the XML feed. TemparatureUnit The unit of the temperature returned by the XML feed iconId The id of the icon to be used. Currently 48 icons from 0 to 47 are available. WeatherDescription The Weather Description Phrase returned by the feed. Link1url The url to the first promo link Link1Text The text for the first promo link Link2url The url to the second promo link Link2Text The text for the second promo link Link3url The url to the third promo link Link3Text The text for the third promo link Link4url The url to the fourth promo link Link4Text The text for the fourth promo link Every time when the service runs, the application will update the database columns from the XOAP data feed. When the application starts, It is going to get the data as XML from the url. This demonstration uses LINQ to extract the necessary data from the fetched XML. The following are the code segment for extracting data from the weather XML using LINQ. // first, create an instance of the XDocument class with the XOAP URL. replace **** with the corresponding values. XDocument weather = XDocument.Load("http://xoap.weather.com/weather/local/BAXX0001?cc=*&link=xoap&prod=xoap&par=***********&key=c*********"); // construct a query using LINQ var feedResult = from item in weather.Descendants() select new { unit = item.Element("head").Element("ut").Value, temp = item.Element("cc").Element("tmp").Value, tempDate = item.Element("cc").Element("lsup").Value, iconId = item.Element("cc").Element("icon").Value, description = item.Element("cc").Element("t").Value, links = from link in item.Elements("lnks").Elements("link") select new { url = link.Element("l").Value, text = link.Element("t").Value } }; // Load the root node to a variable, you may use foreach construct instead. var item1 = feedResult.First(); *If you want to learn more about LINQ and XML, read this nice blog from Scott GU. http://weblogs.asp.net/scottgu/archive/2007/08/07/using-linq-to-xml-and-how-to-build-a-custom-rss-feed-reader-with-it.aspx Now you have all the required values in item1. For e.g. if you want to get the temperature, use item1.temp; Now I just need to execute an SQL query against the database. See the connection part. using (SqlConnection conn = new SqlConnection(@"Data Source=sreeju\sqlexpress;Initial Catalog=Sample;Integrated Security=True")) { string strSql = @"update tblweather set lastupdated=getdate(), temparatureDateTime = @temparatureDateTime, temparature=@temparature, temparatureUnit=@temparatureUnit, iconId = @iconId, description=@description, link1url=@link1url, link1text=@link1text, link2url=@link2url, link2text=@link2text,link3url=@link3url, link3text=@link3text,link4url=@link4url, link4text=@link4text"; SqlCommand comm = new SqlCommand(strSql, conn); comm.Parameters.AddWithValue("temparatureDateTime", item1.tempDate); comm.Parameters.AddWithValue("temparature", item1.temp); comm.Parameters.AddWithValue("temparatureUnit", item1.unit); comm.Parameters.AddWithValue("description", item1.description); comm.Parameters.AddWithValue("iconId", item1.iconId); var lstLinks = item1.links; comm.Parameters.AddWithValue("link1url", lstLinks.ElementAt(0).url); comm.Parameters.AddWithValue("link1text", lstLinks.ElementAt(0).text); comm.Parameters.AddWithValue("link2url", lstLinks.ElementAt(1).url); comm.Parameters.AddWithValue("link2text", lstLinks.ElementAt(1).text); comm.Parameters.AddWithValue("link3url", lstLinks.ElementAt(2).url); comm.Parameters.AddWithValue("link3text", lstLinks.ElementAt(2).text); comm.Parameters.AddWithValue("link4url", lstLinks.ElementAt(3).url); comm.Parameters.AddWithValue("link4text", lstLinks.ElementAt(3).text); conn.Open(); comm.ExecuteNonQuery(); conn.Close(); Console.WriteLine("database updated"); } Now click ctrl + f5 to run the service. I got the following output Check your database and make sure, the data is updated with the latest information from the service. (Make sure you inserted one row in the database by entering some values before executing the service. Otherwise you need to modify your application code to count the rows and conditionally perform insert/update query) Display the Weather information in ASP.Net page Now you got all the data in the database. You just need to create a web application and display the data from the database. I created a new ASP.Net web application with a default.aspx page. In order to comply with the terms of weather.com, You need to use Weather.com logo along with the weather display. You can find the necessary logos to use under the folder “logos” in the SDK. Additionally copy any of the icon set from the folder “icons” to your web application. I used the 93x93 icon set. You are free to use any other sizes available. The design view of the page in VS2010 looks similar to the following. The page contains a heading, an image control (for displaying the weather icon), 2 label controls (for displaying temperature and weather description), 4 hyperlinks (for displaying the 4 promo links returned by the XOAP service) and weather.com logo with hyperlink to the weather.com home page. I am going to write code that will update the values of these controls from the values stored in the database by the service application as mentioned in the previous step. Go to the code behind file for the webpage, enter the following code under Page_Load event handler. using (SqlConnection conn = new SqlConnection(@"Data Source=sreeju\sqlexpress;Initial Catalog=Sample;Integrated Security=True")) { SqlCommand comm = new SqlCommand("select top 1 * from tblweather", conn); conn.Open(); SqlDataReader reader = comm.ExecuteReader(); if (reader.Read()) { lblTemparature.Text = reader["temparature"].ToString() + "&deg;" + reader["temparatureUnit"].ToString(); lblWeatherDescription.Text = reader["description"].ToString(); imgWeather.ImageUrl = "icons/" + reader["iconId"].ToString() + ".png"; lnk1.Text = reader["link1text"].ToString(); lnk1.NavigateUrl = reader["link1url"].ToString(); lnk2.Text = reader["link2text"].ToString(); lnk2.NavigateUrl = reader["link2url"].ToString(); lnk3.Text = reader["link3text"].ToString(); lnk3.NavigateUrl = reader["link3url"].ToString(); lnk4.Text = reader["link4text"].ToString(); lnk4.NavigateUrl = reader["link4url"].ToString(); } conn.Close(); } Press ctrl + f5 to run the page. You will see the following output. That’s it. You need to configure the console application to run every 25 minutes so that the database is updated. Also you can fetch the forecast information and store those in the database, and then retrieve it later in your web page. Since the data resides in your database, you have the full control over your display. You need to make sure your website comply with weather.com license requirements. If you want to get the source code of this walkthrough through the application, post your email address below. Hope you enjoy the reading.

    Read the article

  • Execption Error in c#

    - by Kumu
    using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using System.Runtime.Serialization.Formatters.Binary; namespace FoolballLeague { public partial class MainMenu : Form { FootballLeagueDatabase footballLeagueDatabase; Game game; Login login; public MainMenu() { InitializeComponent(); changePanel(1); } public MainMenu(FootballLeagueDatabase footballLeagueDatabaseIn) { InitializeComponent(); footballLeagueDatabase = footballLeagueDatabaseIn; } private void Form_Loaded(object sender, EventArgs e) { } private void gameButton_Click(object sender, EventArgs e) { int option = 0; changePanel(option); } private void scoreboardButton_Click(object sender, EventArgs e) { int option = 1; changePanel(option); } private void changePanel(int optionIn) { gamePanel.Hide(); scoreboardPanel.Hide(); string title = "Football League System"; switch (optionIn) { case 0: gamePanel.Show(); this.Text = title + " - Game Menu"; break; case 1: scoreboardPanel.Show(); this.Text = title + " - Display Menu"; break; } } private void logoutButton_Click(object sender, EventArgs e) { login = new Login(); login.Show(); this.Hide(); } private void addGameButton_Click(object sender, EventArgs e) { if ((homeTeamTxt.Text.Length) == 0) MessageBox.Show("You must enter a Home Team"); else if (homeScoreUpDown.Value > 9 || homeScoreUpDown.Minimum < 0) MessageBox.Show("You must enter one digit between 0 and 9"); else if ((awayTeamTxt.Text.Length) == 0) MessageBox.Show("You must enter a Away Team"); else if (homeScoreUpDown.Value > 9 || homeScoreUpDown.Value < 0) MessageBox.Show("You must enter one digit between 0 to 9"); else { //checkGameInputFields(); game = new Game(homeTeamTxt.Text, int.Parse(homeScoreUpDown.Value.ToString()), awayTeamTxt.Text, int.Parse(awayScoreUpDown.Value.ToString())); MessageBox.Show("Home Team -" + '\t' + homeTeamTxt.Text + '\t' + "and" + '\r' + "Away Team -" + '\t' + awayTeamTxt.Text + '\t' + "created"); footballLeagueDatabase.AddGame(game); //clearCreateStudentInputFields(); } } private void timer1_Tick(object sender, EventArgs e) { displayDateAndTime(); } private void displayDateAndTime() { dateLabel.Text = DateTime.Today.ToLongDateString(); timeLabel.Text = DateTime.Now.ToShortTimeString(); } private void displayResultsButton_Click(object sender, EventArgs e) { Game game = new Game(homeTeamTxt.Text, int.Parse(homeScoreUpDown.Value.ToString()), awayTeamTxt.Text, int.Parse(awayScoreUpDown.Value.ToString())); gameResultsListView.Items.Clear(); gameResultsListView.View = View.Details; ListViewItem row = new ListViewItem(); row.SubItems.Add(game.HomeTeam.ToString()); row.SubItems.Add(game.HomeScore.ToString()); row.SubItems.Add(game.AwayTeam.ToString()); row.SubItems.Add(game.AwayScore.ToString()); gameResultsListView.Items.Add(row); } private void displayGamesButton_Click(object sender, EventArgs e) { Game game = new Game("Home", 2, "Away", 4);//homeTeamTxt.Text, int.Parse(homeScoreUpDown.Value.ToString()), awayTeamTxt.Text, int.Parse(awayScoreUpDown.Value.ToString())); modifyGamesListView.Items.Clear(); modifyGamesListView.View = View.Details; ListViewItem row = new ListViewItem(); row.SubItems.Add(game.HomeTeam.ToString()); row.SubItems.Add(game.HomeScore.ToString()); row.SubItems.Add(game.AwayTeam.ToString()); row.SubItems.Add(game.AwayScore.ToString()); modifyGamesListView.Items.Add(row); } } } This is the whole code and I got same error like previous question. Unhandled Execption has occuredin you application.If you click...............click Quit.the application will close immediately. Object reference not set to an instance of an object. And the following details are in the error message. See the end of this message for details on invoking just-in-time (JIT) debugging instead of this dialog box. ***** Exception Text ******* System.NullReferenceException: Object reference not set to an instance of an object. at FoolballLeague.MainMenu.addGameButton_Click(Object sender, EventArgs e) in C:\Users\achini\Desktop\FootballLeague\FootballLeague\MainMenu.cs:line 91 at System.Windows.Forms.Control.OnClick(EventArgs e) at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ButtonBase.WndProc(Message& m) at System.Windows.Forms.Button.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) ***** Loaded Assemblies ******* mscorlib Assembly Version: 2.0.0.0 Win32 Version: 2.0.50727.4927 (NetFXspW7.050727-4900) CodeBase: file:///C:/Windows/Microsoft.NET/Framework64/v2.0.50727/mscorlib.dll ---------------------------------------- FootballLeague Assembly Version: 1.0.0.0 Win32 Version: 1.0.0.0 CodeBase: file:///C:/Users/achini/Desktop/FootballLeague/FootballLeague/bin/Debug/FootballLeague.exe ---------------------------------------- System.Windows.Forms Assembly Version: 2.0.0.0 Win32 Version: 2.0.50727.4927 (NetFXspW7.050727-4900) CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System.Windows.Forms/2.0.0.0__b77a5c561934e089/System.Windows.Forms.dll ---------------------------------------- System Assembly Version: 2.0.0.0 Win32 Version: 2.0.50727.4927 (NetFXspW7.050727-4900) CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System/2.0.0.0__b77a5c561934e089/System.dll ---------------------------------------- System.Drawing Assembly Version: 2.0.0.0 Win32 Version: 2.0.50727.4927 (NetFXspW7.050727-4900) CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System.Drawing/2.0.0.0__b03f5f7f11d50a3a/System.Drawing.dll ---------------------------------------- System.Configuration Assembly Version: 2.0.0.0 Win32 Version: 2.0.50727.4927 (NetFXspW7.050727-4900) CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System.Configuration/2.0.0.0__b03f5f7f11d50a3a/System.Configuration.dll ---------------------------------------- System.Xml Assembly Version: 2.0.0.0 Win32 Version: 2.0.50727.4927 (NetFXspW7.050727-4900) CodeBase: file:///C:/Windows/assembly/GAC_MSIL/System.Xml/2.0.0.0__b77a5c561934e089/System.Xml.dll ***** JIT Debugging ******* To enable just-in-time (JIT) debugging, the .config file for this application or computer (machine.config) must have the jitDebugging value set in the system.windows.forms section. The application must also be compiled with debugging enabled. For example: When JIT debugging is enabled, any unhandled exception will be sent to the JIT debugger registered on the computer rather than be handled by this dialog box. I need to add the games to using the addGameButton and the save those added games and display them in the list view (gameResultsListView). Now I can added a game and display in the list view.But when I pressed the button addGameButton I got the above error message. If you can please give me a solution to this problem.

    Read the article

  • BI-Applications Special Price Promotion for Partners

    - by Mike.Hallett(at)Oracle-BI&EPM
    Partners should keep in mind the “Midsize Market” pricing promotion for BI-Applications solution packages, with reduced minimums applicable to Oracle's Business Intelligence Products, and a pre-approved 50% discount. ·       Partners additionally get their normal e-business reseller discount. This now makes it most attractive to offer the pre-built BI-Applications such as Manufacturing Analytics, Financial Analytics, Procurement and Spend Analytics, Project Analytics, and Human Resources Analytics, to both customers newly implementing Oracle ERP, and for the many existing Oracle ERP (eBusiness suite, Peoplesoft and JDE) customers. To answer any questions, and to get the partner document with further details of this offer, or to work with us on our local sales campaigns targeting existing ERP customers, please send your query to Mike[email protected] or [email protected]: or discuss it with your local Oracle Sales or Channel representative for Applications to Midsize Enterprises.  This promotion is ONLY for End Customers whose organisations have an Annual Revenue (or Public Sector Budget) below $500 million, and who are based in Europe, the Middle East or Africa. For more information see the orginal article, “New fy13 BI-Applications Price Promotion for MIDSIZE CUSTOMERS”  and send your query to Mike[email protected].

    Read the article

  • PHP find first of occurrence of string

    - by mike
    I have a string of data like below and I've been struggling trying to figure out how to split it up so that I can use it efficiently. "United States FirstName: Mike LastName: Wolf City: Chicago" I need to split up the string in to substrings and the list may not always be in the same order. For example it could vary like below: "United States City: Chicago FirstName: Mike LastName: Wolf" "United States FirstName: City: Chicago Mike LastName: Wolf" I need to find which parameter comes first after 'United States'. It could be 'City:', 'FirstName:' or 'LastName:'. And, I also need to know the start position of the first parameter. Thanks in advance!

    Read the article

  • Silverlight Cream for December 08, 2010 -- #1005

    - by Dave Campbell
    In this Issue: Peter Kuhn, David Anson, Jesse Liberty, Mike Taulty(-2-, -3-), Kunal Chowdhury, Jeremy Likness, Martin Krüger, Beth Massi(-2-, -3-)/ Above the Fold: Silverlight: "Rebuilding the PDC 2010 Silverlight Application (Part 1)" Mike Taulty WP7: "WP7: Glossy text block custom control" Martin Krüger Lightswitch: "How to Create a Screen with Multiple Search Parameters in LightSwitch" Beth Massi From SilverlightCream.com: Requirements of and pitfalls in Windows Phone 7 serialization Peter Kuhn discusses Data Contract Serializer issuses on WP7 and how to work around them. Managed implementation of CRC32 and MD5 algorithms updated; new release of ComputeFileHashes for Silverlight, WPF, and the command-line! David Anson ties up some loose ends from a prior post on hash functions, and updates his CRC32 and MD5 algorithms. Windows Phone From Scratch #9 – Visual State Jesse Liberty's latest Windows Phone from Scratch tutorial up... and is on the Visual State... he extends a Button and codes up the State Transitions. Rebuilding the PDC 2010 Silverlight Application (Part 1) Mike Taulty has taken the time to rebuild the PDC2010 Silverlight App that folks wanted the source for... and he's taking multiple posts to explain the heck out of it. This first one is mostly infrastructure. Rebuilding the PDC 2010 Silverlight Application (Part 2) In the 2nd post of the series, Mike Taulty is handling the In/Out of Browser business because he eventually is going to be going OOB. Rebuilding the PDC 2010 Silverlight Application (Part 3) Part 3 finds Mike Taulty delving into WCF Data Services and getting some data on the screen. Paginating Records in Silverlight DataGrid using PagedCollectionView Kunal Chowdhury continues with his investigation of the PagedCollectionView with this post on Pagination of your data. Old School Silverlight Effects If you haven't seen Jeremy Likness' 'Old School' Effects page yet, go just for the entertainment... you'll find yourself hanging around for the code :) WP7: Glossy text block custom control Martin Krüger's latest post is a very cool custom control for WP7 that displays Glossy text... it ain't Metro, but it looks pretty nice... some of it almost like etched text. How to Create a Screen with Multiple Search Parameters in LightSwitch Looks like Beth Massi got a few Lightswitch posts in while I wasn't looking. First up is this one on a multiple-parameter search screen. Adding Static Images and Logos to LightSwitch Applications In the 2nd post, Beth Massi shows how to add your own static images and logos to Lightswitch apps... in response to reader questions. Getting the Most out of LightSwitch Summary Properties In her latest post, Beth Massi explains what Summary Properties are in Lightswitch and how to use them to get the best results for your users. Stay in the 'Light! Twitter SilverlightNews | Twitter WynApse | WynApse.com | Tagged Posts | SilverlightCream Join me @ SilverlightCream | Phoenix Silverlight User Group Technorati Tags: Silverlight    Silverlight 3    Silverlight 4    Windows Phone MIX10

    Read the article

  • Adding rows to a data-bound DataGridView [Winforms]

    - by Mishko
    I want to bind a table from a database to a DataGridView, but I want to also add one more row with a sum of the values in the columns with indexes 3,4,7,8,9... How can I do that? Thanks! DataTable table1 = new DataTable(); double brutoUkupno1 = 0; double porezUkupno1 = 0; double doprinosUkupno1 = 0; double netoUkupno1 = 0; double doprinosTeretUkupno1 = 0; double topliObrokUkupno1 = 0; double regresUkupno1 = 0; Connection con = new Connection(); table1 = con.boundTable(month, Convert.ToInt32(year)); //This is method which returns DataTable table1.Rows.Add(null, null, null, null, null, null, null, null, null, null, null, null, null, null); table1.Rows.Add(null, null, null, null, null, null, null, null, null, null, null, null, null, null); dgv2.Visible = true; dgv2.DataSource = table1; for (int i = 0; i < dgv2.RowCount - 2; i++) { topliObrokUkupno1 += Convert.ToDouble(dgv2.Rows[i].Cells[7].Value); regresUkupno1 += Convert.ToDouble(dgv2.Rows[i].Cells[8].Value); brutoUkupno1 += Convert.ToDouble(dgv2.Rows[i].Cells[9].Value); porezUkupno1 += Convert.ToDouble(dgv2.Rows[i].Cells[10].Value); doprinosUkupno1 += Convert.ToDouble(dgv2.Rows[i].Cells[11].Value); netoUkupno1 += Convert.ToDouble(dgv2.Rows[i].Cells[12].Value); doprinosTeretUkupno1 += Convert.ToDouble(dgv2.Rows[i].Cells[13].Value); //Now I am having problems with this below, putting things above to dgv2 : } dgv2.Rows[dgv2.Rows.Count - 1].Cells[0].Value = "Ukupno"; dgv2.Rows[dgv2.Rows.Count - 1].Cells[3].Value = month.ToString(); dgv2.Rows[dgv2.Rows.Count - 1].Cells[4].Value = year.ToString(); dgv2.Rows[dgv2.Rows.Count - 1].Cells[7].Value = topliObrokUkupno1.ToString(); dgv2.Rows[dgv2.Rows.Count - 1].Cells[8].Value = regresUkupno1.ToString(); dgv2.Rows[dgv2.Rows.Count - 1].Cells[9].Value = brutoUkupno1.ToString(); dgv2.Rows[dgv2.Rows.Count - 1].Cells[10].Value = porezUkupno1.ToString(); dgv2.Rows[dgv2.Rows.Count - 1].Cells[11].Value = doprinosUkupno1.ToString(); dgv2.Rows[dgv2.Rows.Count - 1].Cells[12].Value = netoUkupno1.ToString(); dgv2.Rows[dgv2.Rows.Count - 1].Cells[13].Value = doprinosTeretUkupno1.ToString(); dgv2.Rows[dgv2.RowCount - 2].Height = 3; dgv2.Rows[dgv2.RowCount - 2].DefaultCellStyle.BackColor = Color.Black;

    Read the article

  • int, short, byte performance in back-to-back for-loops

    - by runrunraygun
    (background: http://stackoverflow.com/questions/1097467/why-should-i-use-int-instead-of-a-byte-or-short-in-c) To satisfy my own curiosity about the pros and cons of using the "appropriate size" integer vs the "optimized" integer i wrote the following code which reinforced what I previously held true about int performance in .Net (and which is explained in the link above) which is that it is optimized for int performance rather than short or byte. DateTime t; long a, b, c; t = DateTime.Now; for (int index = 0; index < 127; index++) { Console.WriteLine(index.ToString()); } a = DateTime.Now.Ticks - t.Ticks; t = DateTime.Now; for (short index = 0; index < 127; index++) { Console.WriteLine(index.ToString()); } b=DateTime.Now.Ticks - t.Ticks; t = DateTime.Now; for (byte index = 0; index < 127; index++) { Console.WriteLine(index.ToString()); } c=DateTime.Now.Ticks - t.Ticks; Console.WriteLine(a.ToString()); Console.WriteLine(b.ToString()); Console.WriteLine(c.ToString()); This gives roughly consistent results in the area of... ~950000 ~2000000 ~1700000 which is in line with what i would expect to see. However when I try repeating the loops for each data type like this... t = DateTime.Now; for (int index = 0; index < 127; index++) { Console.WriteLine(index.ToString()); } for (int index = 0; index < 127; index++) { Console.WriteLine(index.ToString()); } for (int index = 0; index < 127; index++) { Console.WriteLine(index.ToString()); } a = DateTime.Now.Ticks - t.Ticks; the numbers are more like... ~4500000 ~3100000 ~300000 Which I find puzzling. Can anyone offer an explanation? NOTE: In the interest of compairing like for like i've limited the loops to 127 because of the range of the byte value type. Also this is an act of curiosity not production code micro-optimization.

    Read the article

  • Converting time to Military

    - by Chris
    Maybe I'm seeing things.. In an attempt to turn a date with a format of "mm/dd/yyyy hh:mm:ss PM" into military time, the following replacement of a row value does not seem to take. Even though I am sure I have done this before (with column values other than dates). Is there some reason that row["adate"] would not accept a value assigned to it in this case? DateTime oos = DateTime.Parse(row["adate"].ToString()); row["adate"] = oos.Month.ToString() + "/" + oos.Day.ToString() + "/" + oos.Year.ToString() + " " + oos.Hour.ToString() + ":" + oos.Minute.ToString();

    Read the article

  • Abstract out repeated code

    - by CookieMonster
    The code in this event is repeated exactly in two other event handlers. How do I put the repeated code into a method and call that method from the event handlers so I only have to maintain it in one place? I'm not sure how to pass the event args to the calling method. protected void gvDocAssoc_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { if ((Convert.ToString(DataBinder.Eval(e.Row.DataItem, "DETAIL_TYPE_DESC")) == "Transcript") && (Convert.ToString(DataBinder.Eval(e.Row.DataItem, "INSTITUTION_CODE")) == "")) { e.Row.BackColor = System.Drawing.Color.Red; } if ((Convert.ToString(DataBinder.Eval(e.Row.DataItem, "DETAIL_TYPE_DESC")) == "Certified Diploma") && (Convert.ToString(DataBinder.Eval(e.Row.DataItem, "INSTITUTION_CODE")) == "")) { e.Row.BackColor = System.Drawing.Color.Red; } if ((Convert.ToString(DataBinder.Eval(e.Row.DataItem, "DOC_TYPE_DESC")) == "Post Graduate conditions") && (Convert.ToString(DataBinder.Eval(e.Row.DataItem, "INSTITUTION_CODE")) == "")) { e.Row.BackColor = System.Drawing.Color.Red; } } }

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >