Search Results

Search found 1234 results on 50 pages for 'enum'.

Page 21/50 | < Previous Page | 17 18 19 20 21 22 23 24 25 26 27 28  | Next Page >

  • Optimize GROUP BY&ORDER BY query

    - by Jan Hancic
    I have a web page where users upload&watch videos. Last week I asked what is the best way to track video views so that I could display the most viewed videos this week (videos from all dates). Now I need some help optimizing a query with which I get the videos from the database. The relevant tables are this: video (~239371 rows) VID(int), UID(int), title(varchar), status(enum), type(varchar), is_duplicate(enum), is_adult(enum), channel_id(tinyint) signup (~115440 rows) UID(int), username(varchar) videos_views (~359202 rows after 6 days of collecting data, so this table will grow rapidly) videos_id(int), views_date(date), num_of_views(int) The table video holds the videos, signup hodls users and videos_views holds data about video views (each video can have one row per day in that table). I have this query that does the trick, but takes ~10s to execute, and I imagine this will only get worse over time as the videos_views table grows in size. SELECT v.VID, v.title, v.vkey, v.duration, v.addtime, v.UID, v.viewnumber, v.com_num, v.rate, v.THB, s.username, SUM(vvt.num_of_views) AS tmp_num FROM video v LEFT JOIN videos_views vvt ON v.VID = vvt.videos_id LEFT JOIN signup s on v.UID = s.UID WHERE v.status = 'Converted' AND v.type = 'public' AND v.is_duplicate = '0' AND v.is_adult = '0' AND v.channel_id <> 10 AND vvt.views_date >= '2001-05-11' GROUP BY vvt.videos_id ORDER BY tmp_num DESC LIMIT 8 And here is a screenshot of the EXPLAIN result: So, how can I optimize this?

    Read the article

  • C# - Naming a value combined "getter/setter" method (WebForms & Binding)

    - by tyndall
    Looking for some help on some names for a project I'm currently working on. I don't have a compsci degree so I don't know what to call this. I have a method called TryToGetSetValue(Direction direction, object value, object valueOnFail) Then there would be a Direction enum public enum Direction { ModelToForm, FormToModel } Background This is a legacy ASP.NET application. The models, database, and mainframe are designed poorly. I can't put in MVP or MVC patterns yet (too much work). ASP.NET code is a ridiculous mess (partial pages, single-page design, 5x the normal amount of jQuery, everything is a jQuery UI dialog). I'm just trying to put in a bridge so then I can do more refactoring over the next year. I have ~200 fields that need to be set on a GET and written back on a POST. I trying not to x2 these 200 fields and have 400 lines of code to support. What would you call my method? enum? Is there so other form of binding that would be easy to use instead? I'm not a fan of the DetailsView or FormView built-ins of ASP.NET WebForms.

    Read the article

  • How can I store an inventory-like list of numbers?

    - by Rachel
    I've got a list of number that I need to keep track of. The numbers are loosely related, but represent distinctly different items. I'd like to keep a list of the numbers but be able to refer to them by name so that I can call them and use them where needed easily. Kind of like an inventory listing, where the numbers all refer to a part ID and I'd like to call them idPart1, idPart2, idPart3 so their purpose is easily identifiable when they are used. What would be the best way to do this? 1)Define a structure. Say, PartIds. A number of int members will be included, part1, part2 etc. To use, an instance of the structure will be created, values assigned to the members, and the numbers will be used by saying struct.member as needed. 2)Define an enumeration. Use part1, part2 as the enum literals. Store the actual values in a vector or list, each one at the index corresponding to the value of the number's name within the enum. Use the enum literals to retrieve the values, list[enumLit]. 3)Something completely different There's nothing else I need to do with the numbers - just look them up every once in a while. Since there's no processing, I kind of think a new class for them is overkill, but I'm willing to be convinced otherwise. Any suggestions?

    Read the article

  • Detecting Inheritence during compile time

    - by Jagannath
    I am unable to figure out why this code is returning false. I had the first version of partial specialization. It did not work, I tried with the second version. It did not work either. UPDATE: I wanted to check if "Derived" is publicly derived from "Base". template<class TBase, class TDerived> struct IsDerived { public: enum { isDerived = false }; }; template<class TBase> struct IsDerived<TBase, TBase> { public: enum { isDerived = true }; }; template<class TBase> struct IsDerived<TBase&, TBase&> { public: enum { isDerived = true }; }; int main() { cout << ((IsDerived<Base&, Derived&>::isDerived) ? "true" : "false") << endl; cout << ((IsDerived<const Derived*, const Base*>::isDerived) ? "true" : "false") << endl; }

    Read the article

  • Is this WPF error handling a good idea ?

    - by Adiel
    I have a multi threaded wpf application with various HW interfaces. I want to react to several HW failures that can happen. For example : one of the interfaces is a temperature sensor and i want that from a certain temp. a meesage would appear and notify the user that it happened. i came up with the follwing design : /// <summary> /// This logic reacts to errors that occur during the system run. /// The reaction is set by the component that raised the error. /// </summary> public class ErrorHandlingLogic : Logic { } the above class would consume ErrorEventData that holds all the information about the error that occurred. public class ErrorEventData : IEventData { #region public enum public enum ErrorReaction { } #endregion public enum #region Private Data Memebers and props private ErrorReaction m_ErrorReaction; public ErrorReaction ErrorReactionValue { get { return m_ErrorReaction; } set { m_ErrorReaction = value; } } private string m_Msg; public string Msg { get { return m_Msg; } set { m_Msg = value; } } private string m_ComponentName; public string ComponentName { get { return m_ComponentName; } set { m_ComponentName = value; } } #endregion Private Data Memebers and props public ErrorEventData(ErrorReaction reaction, string msg, string componenetName) { m_ErrorReaction = reaction; m_Msg = msg; m_ComponentName = componenetName; } } the above ErrorHandlingLogic would decide what to do with the ErrorEventData sent to him from various components of the application. if needed it would be forwarded to the GUI to display a message to the user. so what do you think is it a good design ? thanks, Adiel.

    Read the article

  • anti-if campaign

    - by Andrew Siemer
    I recently ran against a very interesting site that expresses a very interesting idea - the anti-if campaign. You can see this here at www.antiifcampaign.com. I have to agree that complex nested IF statements are an absolute pain in the rear. I am currently on a project that up until very recently had some crazy nested IFs that scrolled to the right for quite a ways. We cured our issues in two ways - we used Windows Workflow Foundation to address routing (or workflow) concerns. And we are in the process of implementing all of our business rules utilizing ILOG Rules for .NET (recently purchased by IBM!!). This for the most part has cured our nested IF pains...but I find myself wondering how many people cure their pains in the manner that the good folks at the AntiIfCampaign suggest (see an example here) by creating numerous amounts of abstract classes to represent a given scenario that was originally covered by the nested IF. I wonder if another way to address the removal of this complexity might also be in using an IoC container such as StructureMap to move in and out of different bits of functionality. Either way... Question: Given a scenario where I have a nested complex IF or SWITCH statement that is used to evaluate a given type of thing (say evaluating an Enum) to determine how I want to handle the processing of that thing by enum type - what are some ways to do the same form of processing without using the IF or SWITCH hierarchical structure? public enum WidgetTypes { Type1, Type2, Type3, Type4 } ... WidgetTypes _myType = WidgetTypes.Type1; ... switch(_myType) { case WidgetTypes.Type1: //do something break; case WidgetTypes.Type2: //do something break; //etc... }

    Read the article

  • passing an "unknown enumeration" to a method

    - by firoso
    I'm currently trying to make a class that can register strings as identifiers and accociate them with different types of Enumerations, these enumerations are being evaluated only in so much that I am ensuring that when it's used, that the parameter passed to broadcast (messageType) is an instance of the associated Enum Type. This would work something like this: Diagnostics.RegisterIdentifier("logger", typeof(TestEnum)); Diagnostics.Broadcast("logger", TestEnum.Info, null, "Hello World", null); here's the code I currently have, I need to be able to verify that messageTypesEnum is contained in messageTypesFromIdentifier. private static Dictionary<string, Type> identifierMessageTypeMapping = new Dictionary<string, Type>(); private static List<IListener> listeners = new List<IListener>(); public static void RegisterIdentifier(string identifier, Type messageTypesEnum) { if (messageTypesEnum.BaseType.FullName == "System.Enum") { identifierMessageTypeMapping.Add(identifier, messageTypesEnum); } else { throw new ArgumentException("Expected type of messageTypesEnum to derive from System.Enum", "messageTypesEnum"); } } public static void Broadcast(string identifier, object messageType, string metaIdentifier, string message, Exception exception) { if (identifierMessageTypeMapping.ContainsKey(identifier)) { Type messageTypesFromIdentifier = identifierMessageTypeMapping[identifier]; foreach (var listener in listeners) { DiagnosticsEvent writableEvent = new DiagnosticsEvent(identifier, messageType, metaIdentifier, message, exception); listener.Write(writableEvent); } } }

    Read the article

  • How do I get events to execute on the "main thread"

    - by William DiStefano
    I have 2 classes, one is frmMain a windows form and the other is a class in vb.NET 2003. frmMain contains a start button which executes the monitor function in the other class. My question is, I am manually adding the event handlers -- when the events are executed how do I get them to excute on the "main thread". Because when the tooltip balloon pops up at the tray icon it displays a second tray icon instead of popping up at the existing tray icon. I can confirm that this is because the events are firing on new threads because if I try to display a balloon tooltip from frmMain it will display on the existing tray icon. Here is a part of the second class (not the entire thing): Friend Class monitorFolders Private _watchFolder As System.IO.FileSystemWatcher = New System.IO.FileSystemWatcher Private _eType As evtType Private Enum evtType changed created deleted renamed End Enum Friend Sub monitor(ByVal path As String) _watchFolder.Path = path 'Add a list of Filter to specify _watchFolder.NotifyFilter = IO.NotifyFilters.DirectoryName _watchFolder.NotifyFilter = _watchFolder.NotifyFilter Or IO.NotifyFilters.FileName _watchFolder.NotifyFilter = _watchFolder.NotifyFilter Or IO.NotifyFilters.Attributes 'Add event handlers for each type of event that can occur AddHandler _watchFolder.Changed, AddressOf change AddHandler _watchFolder.Created, AddressOf change AddHandler _watchFolder.Deleted, AddressOf change AddHandler _watchFolder.Renamed, AddressOf Rename 'Start watching for events _watchFolder.EnableRaisingEvents = True End Sub Private Sub change(ByVal source As Object, ByVal e As System.IO.FileSystemEventArgs) If e.ChangeType = IO.WatcherChangeTypes.Changed Then _eType = evtType.changed notification() End If If e.ChangeType = IO.WatcherChangeTypes.Created Then _eType = evtType.created notification() End If If e.ChangeType = IO.WatcherChangeTypes.Deleted Then _eType = evtType.deleted notification() End If End Sub Private Sub notification() _mainForm.NotifyIcon1.ShowBalloonTip(500, "Folder Monitor", "A file has been " + [Enum].GetName(GetType(evtType), _eType), ToolTipIcon.Info) End Sub End Class

    Read the article

  • How to write a "thread safe" function in C ?

    - by Andrei Ciobanu
    Hello I am writing some data structures in C, and I've realized that their associated functions aren't thread safe. The i am writing code uses only standard C, and I want to achieve some sort of 'synchronization'. I was thinking to do something like this: enum sync_e { TRUE, FALSE }; typedef enum sync_e sync; struct list_s { //Other stuff struct list_node_s *head; struct list_node_s *tail; enum sync_e locked; }; typedef struct list_s list; , to include a "boolean" field in the list structure that indicates the structures state: locked, unlocked. For example an insertion function will be rewritten this way: int list_insert_next(list* l, list_node *e, int x){ while(l->locked == TRUE){ /* Wait */ } l->locked = TRUE; /* Insert element */ /* -------------- */ l->locked = FALSE; return (0); } While operating on the list the 'locked' field will be set to TRUE, not allowing any other alterations. After operation completes the 'locked' field will be again set to 'TRUE'. Is this approach good ? Do you know other approaches (using only standard C).

    Read the article

  • C++ private inheritance and static members/types

    - by WearyMonkey
    I am trying to stop a class from being able to convert its 'this' pointer into a pointer of one of its interfaces. I do this by using private inheritance via a middle proxy class. The problem is that I find private inheritance makes all public static members and types of the base class inaccessible to all classes under the inheriting class in the hierarchy. class Base { public: enum Enum { value }; }; class Middle : private Base { }; class Child : public Middle { public: void Method() { Base::Enum e = Base::value; // doesn't compile BAD! Base* base = this; // doesn't compile GOOD! } }; I've tried this in both VS2008 (the required version) and VS2010, neither work. Can anyone think of a workaround? Or a different approach to stopping the conversion? Also I am curios of the behavior, is it just a side effect of the compiler implementation, or is it by design? If by design, then why? I always thought of private inheritance to mean that nobody knows Middle inherits from Base. However, the exhibited behavior implies private inheritance means a lot more than that, in-fact Child has less access to Base than any namespace not in the class hierarchy!

    Read the article

  • How can I handle all my errors/messages in one place on an Asp.Net page?

    - by Atomiton
    Hi all, I'm looking for some guidance here. On my site I put things in Web user controls. For example, I will have a NewsItem Control, an Article Control, a ContactForm control. These will appear in various places on my site. What I'm looking for is a way for these controls to pass messages up to the Page that they exist on. I don't want to tightly couple them, so I think I will have to do this with Events/Delegates. I'm a little unclear as to how I would implement this, though. A couple of examples: 1 A contact form is submitted. After it's submitted, instead of replacing itself with a "Your mail has been sent" which limits the placement of that message, I'd like to just notify the page that the control is on with a Status message and perhaps a suggested behaviour. So, a message would include the text to render as well as an enum like DisplayAs.Popup or DisplayAs.Success 2 An Article Control queries the database for an Article object. Database returns an Exception. Custom Exception is passed to the page along with the DisplayAs.Error enum. The page handles this error and displays it wherever the errors go. I'm trying to accomplish something similar to the ValidationSummary Control, except that I want the page to be able to display the messages as the enum feels fit. Again, I don't want to tightly bind or rely a control existing on the Page. I want the controls to raise these events, but the page can ignore them if it wants. Am I going about this the right way? I'd love a code sample just to get me started. I know this is a more involved question, so I'll wait longer before voting/choosing the answers.

    Read the article

  • XmlSerializer construction with same named extra types

    - by NoizWaves
    Hey, I am hitting trouble constructing an XmlSerializer where the extra types contains types with the same Name (but unique Fullname). Below is an example that illustrated my scenario. Type definitions in external assembly I cannot manipulate: public static class Wheel { public enum Status { Stopped, Spinning } } public static class Engine { public enum Status { Idle, Full } } Class I have written and have control over: public class Car { public Wheel.Status WheelStatus; public Engine.Status EngineStatus; public static string Serialize(Car car) { var xs = new XmlSerializer(typeof(Car), new[] {typeof(Wheel.Status),typeof(Engine.Status)}); var output = new StringBuilder(); using (var sw = new StringWriter(output)) xs.Serialize(sw, car); return output.ToString(); } } The XmlSerializer constructor throws a System.InvalidOperationException with Message "There was an error reflecting type 'Engine.Status'" This exception has an InnerException of type System.InvalidOperationException and with Message "Types 'Wheel.Status' and 'Engine.Status' both use the XML type name, 'Status', from namespace ''. Use XML attributes to specify a unique XML name and/or namespace for the type." Given that I am unable to alter the enum types, how can I construct an XmlSerializer that will serialize Car successfully?

    Read the article

  • What do I need to do if I want all typeof(MyEnum)'s to be handled with MyEnumModelBinder?

    - by Byron Sommardahl
    I have an Enum that appears in several of my models. For the most part, the DefaultModelBinder handles binding to my models beautifully. That it, until it gets to my Enum... it always returns the first member in the Enum no matter what is handed it by the POST. My googling leads me to believe I need to have a model binder that knows how to handle Enums. I found an excellent article on a possible custom modelBinder for Enums: http://eliasbland.wordpress.com/2009/08/08/enumeration-model-binder-for-asp-net-mvc/. I've since implemented that modelBinder and registered it in my global.asax: ModelBinders.Binders[typeof (MyEnum)] = new EnumBinder<MyEnum>(MyEnum.MyDefault); For some reason, the EnumBinder< isn't being called when the model I'm binding to has MyEnum. I have a breakpoint in the .BindModel() method and it never break. Also, my model hasn't changed after modelBinding. Have I done everything? What am I missing here?

    Read the article

  • What is a modern C++ approach to structures containing symbolic constants?

    - by Ken
    enum bool { FALSE = 0, TRUE = 1 }; I'm wondering how to translate this in a modern C++ approach and if there is a well suited container for that; i know that the enum are not really that appreciated, but i can't think about a real alternative in the C++ world. What if would like to associate the execution of a particular method with a state? Ok, this is the part where i will be more verbose. I would like to stress the fact that i'm asking about structures symbolic constants and not about TRUE and FALSE, i'm not that "needy". Suppose that i have a structure that can represent several states with their own constants enum semaphore { GREEN = 0, ORANGE = 1, RED = 2 }; this is C code, now my question is about how to do the same in C++ if there is a better way. My question continue when i ask about the possibility to do something like an automatic triggering when a change of state will occur, for example: int main{ ... semaphore = 1; ... } and without any extra statements this has to trigger a method() just because the semaphore is now orange. I hope that is more clear now.

    Read the article

  • avoiding code duplication in Rails 3 models

    - by Dustin Frazier
    I'm working on a Rails 3.1 application where there are a number of different enum-like models that are stored in the database. There is a lot of identical code in these models, as well as in the associated controllers and views. I've solved the code duplication for the controllers and views via a shared parent controller class and the new view/layout inheritance that's part of Rails 3. Now I'm trying to solve the code duplication in the models, and I'm stuck. An example of one of my enum models is as follows: class Format < ActiveRecord::Base has_and_belongs_to_many :videos attr_accessible :name validates :name, presence: true, length: { maximum: 20 } before_destroy :verify_no_linked_videos def verify_no_linked_videos unless self.videos.empty? self.errors[:base] << "Couldn't delete format with associated videos." raise ActiveRecord::RecordInvalid.new self end end end I have four or five other classes with nearly identical code (the association declaration being the only difference). I've tried creating a module with the shared code that they all include (which seems like the Ruby Way), but much of the duplicate code relies on ActiveRecord, so the methods I'm trying to use in the module (validate, attr_accessible, etc.) aren't available. I know about ActiveModel, but that doesn't get me all the way there. I've also tried creating a common, non-persistent parent class that subclasses ActiveRecord::Base, but all of the code I've seen to accomplish this assumes that you won't have subclasses of your non-persistent class that do persist. Any suggestions for how best to avoid duplicating these identical lines of code across many different enum models?

    Read the article

  • Enums and inheritance

    - by devoured elysium
    I will use (again) the following class hierarchy: Event and all the following classes inherit from Event: SportEventType1 SportEventType2 SportEventType3 SportEventType4 I have originally designed the Event class like this: public abstract class Event { public abstract EventType EventType { get; } public DateTime Time { get; protected set; } protected Event(DateTime time) { Time = time; } } with EventType being defined as: public enum EventType { Sport1, Sport2, Sport3, Sport4 } The original idea would be that each SportEventTypeX class would set its correct EventType. Now that I think of it, I think this approach is totally incorrect for two reasons: If I want to later add a new SportEventType class I will have to modify the enum If I later decide to remove one SportEventType that I feel I won't use I'm also in big trouble with the enum. I have a class variable in the Event class that makes, afterall, assumptions about the kind of classes that will inherit from it, which kinda defeats the purpose of inheritance. How would you solve this kind of situation? Define in the Event class an abstract "Description" property, having each child class implement it? Having an Attribute(Annotation in Java!) set its Description variable instead? What would be the pros/cons of having a class variable instead of attribute/annotation in this case? Is there any other more elegant solution out there? Thanks

    Read the article

  • Winbind group lookup painfully slow

    - by Marty
    I am running winbind on an RHEL 6 system. Everything works fine except group lookups, so many commands (including sudo) are painfully slow. I did an strace which shows that winbind looks up every group and every user within each group for the current user. Some of these groups have 20000+ users so a simple sudo can take 60 seconds to complete. I really only care about speeding up the sudo command. Ideal solutions would make it so either: groups with more than X number of users will not be looked up, or sudo bypasses group lookups altogether. Here is my current "smb.conf" for winbind: workgroup = EXAMPLE password server = AD1.EXAMPLE.ORG realm = EXAMPLE.ORG security = ads idmap uid = 10000-19999 idmap gid = 10000-19999 idmap config EXAMPLE:backend = rid idmap config EXAMPLE:range = 10000000-19999999 winbind enum users = no winbind enum groups = no winbind separator = + template homedir = /home/%U template shell = /bin/bash winbind use default domain = yes winbind offline logon = false

    Read the article

  • How can I enable anonymous access to a Samba share under ADS security mode?

    - by hemp
    I'm trying to enable anonymous access to a single service in my Samba config. Authorized user access is working perfectly, but when I attempt a no-password connection, I get this message: Anonymous login successful Domain=[...] OS=[Unix] Server=[Samba 3.3.8-0.51.el5] tree connect failed: NT_STATUS_LOGON_FAILURE The message log shows this error: ... smbd[21262]: [2010/05/24 21:26:39, 0] smbd/service.c:make_connection_snum(1004) ... smbd[21262]: Can't become connected user! The smb.conf is configured thusly: [global] security = ads obey pam restrictions = Yes winbind enum users = Yes winbind enum groups = Yes winbind use default domain = true valid users = "@domain admins", "@domain users" guest account = nobody map to guest = Bad User [evilshare] path = /evil/share guest ok = yes read only = No browseable = No Given that I have 'map to guest = Bad User' and 'guest ok' specified, I don't understand why it is trying to "become connected user". Should it not be trying to "become guest user"?

    Read the article

  • How can I enable anonymous access to a Samba share under ADS security mode?

    - by hemp
    I'm trying to enable anonymous access to a single service in my Samba config. Authorized user access is working perfectly, but when I attempt a no-password connection, I get this message: Anonymous login successful Domain=[...] OS=[Unix] Server=[Samba 3.3.8-0.51.el5] tree connect failed: NT_STATUS_LOGON_FAILURE The message log shows this error: ... smbd[21262]: [2010/05/24 21:26:39, 0] smbd/service.c:make_connection_snum(1004) ... smbd[21262]: Can't become connected user! The smb.conf is configured thusly: [global] security = ads obey pam restrictions = Yes winbind enum users = Yes winbind enum groups = Yes winbind use default domain = true valid users = "@domain admins", "@domain users" guest account = nobody map to guest = Bad User [evilshare] path = /evil/share guest ok = yes read only = No browseable = No Given that I have 'map to guest = Bad User' and 'guest ok' specified, I don't understand why it is trying to "become connected user". Should it not be trying to "become guest user"?

    Read the article

  • How can I properly implement inetcpl.cpl as an external dll?

    - by Kyt
    I have the following 2 sets of code, both of which produce the same results: using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ResetIE { class Program { [DllImport("InetCpl.cpl", SetLastError=true, CharSet=CharSet.Unicode, EntryPoint="ClearMyTracksByProcessW")] public static extern long ClearMyTracksByProcess(IntPtr hwnd, IntPtr hinst, ref TargetHistory lpszCmdLine, FormWindowState nCmdShow); static void Main(string[] args) { TargetHistory th = TargetHistory.CLEAR_TEMPORARY_INTERNET_FILES; ClearMyTracksByProcessW(Process.GetCurrentProcess().Handle, Marshal.GetHINSTANCE(typeof(Program).Module), ref th, FormWindowState.Maximized); Console.WriteLine("Done."); } } and ... static class NativeMethods { [DllImport("kernel32.dll")] public static extern IntPtr LoadLibrary(string dllToLoad); [DllImport("kernel32.dll")] public static extern IntPtr GetProcAddress(IntPtr hModule, string procedureName); [DllImport("kernel32.dll")] public static extern bool FreeLibrary(IntPtr hModule); } public class CallExternalDLL { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate long ClearMyTracksByProcessW(IntPtr hwnd, IntPtr hinst, ref TargetHistory lpszCmdLine, FormWindowState nCmdShow); public static void Clear_IE_Cache() { IntPtr pDll = NativeMethods.LoadLibrary(@"C:\Windows\System32\inetcpl.cpl"); if (pDll == IntPtr.Zero) { Console.WriteLine("An Error has Occurred."); } IntPtr pAddressOfFunctionToCall = NativeMethods.GetProcAddress(pDll, "ClearMyTracksByProcessW"); if (pAddressOfFunctionToCall == IntPtr.Zero) { Console.WriteLine("Function Not Found."); } ClearMyTracksByProcessW cmtbp = (ClearMyTracksByProcessW)Marshal.GetDelegateForFunctionPointer(pAddressOfFunctionToCall, typeof(ClearMyTracksByProcessW)); TargetHistory q = TargetHistory.CLEAR_TEMPORARY_INTERNET_FILES; long result = cmtbp(Process.GetCurrentProcess().Handle, Marshal.GetHINSTANCE(typeof(ClearMyTracksByProcessW).Module), ref q, FormWindowState.Normal); } } both use the following Enum: public enum TargetHistory { CLEAR_ALL = 0xFF, CLEAR_ALL_WITH_ADDONS = 0x10FF, CLEAR_HISTORY = 0x1, CLEAR_COOKIES = 0x2, CLEAR_TEMPORARY_INTERNET_FILES = 0x8, CLEAR_FORM_DATA = 0x10, CLEAR_PASSWORDS = 0x20 } Both methods of doing this compile and run just fine, offering no errors, but both churn endlessly never returning from their work. The PInvoke code was ported from the following VB, which was fairly difficult to track down: Option Explicit Private Enum TargetHistory CLEAR_ALL = &HFF& CLEAR_ALL_WITH_ADDONS = &H10FF& CLEAR_HISTORY = &H1& CLEAR_COOKIES = &H2& CLEAR_TEMPORARY_INTERNET_FILES = &H8& CLEAR_FORM_DATA = &H10& CLEAR_PASSWORDS = &H20& End Enum Private Declare Function ClearMyTracksByProcessW Lib "InetCpl.cpl" _ (ByVal hwnd As OLE_HANDLE, _ ByVal hinst As OLE_HANDLE, _ ByRef lpszCmdLine As Byte, _ ByVal nCmdShow As VbAppWinStyle) As Long Private Sub Command1_Click() Dim b() As Byte Dim o As OptionButton For Each o In Option1 If o.Value Then b = o.Tag ClearMyTracksByProcessW Me.hwnd, App.hInstance, b(0), vbNormalFocus Exit For End If Next End Sub Private Sub Form_Load() Command1.Caption = "??" Option1(0).Caption = "?????????????" Option1(0).Tag = CStr(CLEAR_TEMPORARY_INTERNET_FILES) Option1(1).Caption = "Cookie" Option1(1).Tag = CStr(CLEAR_COOKIES) Option1(2).Caption = "??" Option1(2).Tag = CStr(CLEAR_HISTORY) Option1(3).Caption = "???? ???" Option1(3).Tag = CStr(CLEAR_HISTORY) Option1(4).Caption = "?????" Option1(4).Tag = CStr(CLEAR_PASSWORDS) Option1(5).Caption = "?????" Option1(5).Tag = CStr(CLEAR_ALL) Option1(2).Value = True End Sub The question is simply what am I doing wrong? I need to clear the internet cache, and would prefer to use this method as I know it does what I want it to when it works (rundll32 inetcpl.cpl,ClearMyTracksByProcess 8 works fine). I've tried running both as normal user and admin to no avail. This project is written using C# in VS2012 and compiled against .NET3.5 (must remain at 3.5 due to client restrictions)

    Read the article

  • A ResetBindings on a BindingSource of a Grid also resets ComboBox

    - by Tetsuo
    Hi there, I have a DataGridView with a BindingSource of products. This products have an enum (Producer). For the most text fields (to edit the product) below the DataGridView I have a method RefreshProduct which does a ResetBindings in the end to refresh the DataGridView. There is a ComboBox (cboProducer), too. If I run over the _orderBs.ResetBindings(false) it will reset my cboProducer outside the DataGridView, too. Could you please help me to avoid this? Here follows some code; maybe it is then better to understand. public partial class SelectProducts : UserControl { private AutoCompleteStringCollection _productCollection; private ProductBL _productBL; private OrderBL _orderBL; private SortableBindingList<ProductBE> _listProducts; private ProductBE _selectedProduct; private OrderBE _order; BindingSource _orderBs = new BindingSource(); public SelectProducts() { InitializeComponent(); if (_productBL == null) _productBL = new ProductBL(); if (_orderBL == null) _orderBL = new OrderBL(); if (_productCollection == null) _productCollection = new AutoCompleteStringCollection(); if (_order == null) _order = new OrderBE(); if (_listProducts == null) { _listProducts = _order.ProductList; _orderBs.DataSource = _order; grdOrder.DataSource = _orderBs; grdOrder.DataMember = "ProductList"; } } private void cmdGetProduct_Click(object sender, EventArgs e) { ProductBE product = _productBL.Load(txtProductNumber.Text); _listProducts.Add(product); _orderBs.ResetBindings(false); } private void grdOrder_SelectionChanged(object sender, EventArgs e) { if (grdOrder.SelectedRows.Count > 0) { _selectedProduct = (ProductBE)((DataGridView)(sender)).CurrentRow.DataBoundItem; if (_selectedProduct != null) { txtArticleNumber.Text = _selectedProduct.Article; txtPrice.Text = _selectedProduct.Price.ToString("C"); txtProducerNew.Text = _selectedProduct.ProducerText; cboProducer.DataSource = Enum.GetValues(typeof(Producer)); cboProducer.SelectedItem = _selectedProduct.Producer; } } } private void txtProducerNew_Leave(object sender, EventArgs e) { string property = CommonMethods.GetPropertyName(() => new ProductBE().ProducerText); RefreshProduct(((TextBoxBase)sender).Text, property); } private void RefreshProduct(object value, string property) { if (_selectedProduct != null) { double valueOfDouble; if (double.TryParse(value.ToString(), out valueOfDouble)) { value = valueOfDouble; } Type type = _selectedProduct.GetType(); PropertyInfo info = type.GetProperty(property); if (info.PropertyType.BaseType == typeof(Enum)) { value = Enum.Parse(info.PropertyType, value.ToString()); } try { Convert.ChangeType(value, info.PropertyType, new CultureInfo("de-DE")); info.SetValue(_selectedProduct, value, null); } catch (Exception ex) { throw new WrongFormatException("\"" + value.ToString() + "\" is not a valid value.", ex); } var produktFromList = _listProducts.Single(p => p.Position == _selectedProduct.Position); info.SetValue(produktFromList, value, null); _orderBs.ResetBindings(false); } } private void cboProducer_SelectedIndexChanged(object sender, EventArgs e) { var selectedIndex = ((ComboBox)(sender)).SelectedIndex; switch ((Producer)selectedIndex) { case Producer.ABC: txtProducerNew.Text = Constants.ABC; break; case Producer.DEF: txtProducerNew.Text = Constants.DEF; break; case Producer.GHI: txtProducerNew.Text = Constants.GHI; break; case Producer.Another: txtProducerNew.Text = String.Empty; break; default: break; } string property = CommonMethods.GetPropertyName(() => new ProductBE().Producer); RefreshProduct(selectedIndex, property); } }

    Read the article

  • How can I optimize this subqueried and Joined MySQL Query?

    - by kevzettler
    I'm pretty green on mysql and I need some tips on cleaning up a query. It is used in several variations through out a site. Its got some subquerys derived tables and fun going on. Heres the query: # Query_time: 2 Lock_time: 0 Rows_sent: 0 Rows_examined: 0 SELECT * FROM ( SELECT products . *, categories.category_name AS category, ( SELECT COUNT( * ) FROM distros WHERE distros.product_id = products.product_id) AS distro_count, (SELECT COUNT(*) FROM downloads WHERE downloads.product_id = products.product_id AND WEEK(downloads.date) = WEEK(curdate())) AS true_downloads, (SELECT COUNT(*) FROM views WHERE views.product_id = products.product_id AND WEEK(views.date) = WEEK(curdate())) AS true_views FROM products INNER JOIN categories ON products.category_id = categories.category_id ORDER BY created_date DESC, true_views DESC ) AS count_table WHERE count_table.distro_count > 0 AND count_table.status = 'published' AND count_table.active = 1 LIMIT 0, 8 Heres the explain: +----+--------------------+------------+-------+---------------+-------------+---------+------------------------------------+------+----------------------------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+--------------------+------------+-------+---------------+-------------+---------+------------------------------------+------+----------------------------------------------+ | 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 232 | Using where | | 2 | DERIVED | categories | index | PRIMARY | idx_name | 47 | NULL | 13 | Using index; Using temporary; Using filesort | | 2 | DERIVED | products | ref | category_id | category_id | 4 | digizald_db.categories.category_id | 9 | | | 5 | DEPENDENT SUBQUERY | views | ref | product_id | product_id | 4 | digizald_db.products.product_id | 46 | Using where | | 4 | DEPENDENT SUBQUERY | downloads | ref | product_id | product_id | 4 | digizald_db.products.product_id | 14 | Using where | | 3 | DEPENDENT SUBQUERY | distros | ref | product_id | product_id | 4 | digizald_db.products.product_id | 1 | Using index | +----+--------------------+------------+-------+---------------+-------------+---------+------------------------------------+------+----------------------------------------------+ 6 rows in set (0.04 sec) And the Tables: mysql> describe products; +---------------+--------------------------------------------------+------+-----+-------------------+----------------+ | Field | Type | Null | Key | Default | Extra | +---------------+--------------------------------------------------+------+-----+-------------------+----------------+ | product_id | int(10) unsigned | NO | PRI | NULL | auto_increment | | product_key | char(32) | NO | | NULL | | | title | varchar(150) | NO | | NULL | | | company | varchar(150) | NO | | NULL | | | user_id | int(10) unsigned | NO | MUL | NULL | | | description | text | NO | | NULL | | | video_code | text | NO | | NULL | | | category_id | int(10) unsigned | NO | MUL | NULL | | | price | decimal(10,2) | NO | | NULL | | | quantity | int(10) unsigned | NO | | NULL | | | downloads | int(10) unsigned | NO | | NULL | | | views | int(10) unsigned | NO | | NULL | | | status | enum('pending','published','rejected','removed') | NO | | NULL | | | active | tinyint(1) | NO | | NULL | | | deleted | tinyint(1) | NO | | NULL | | | created_date | datetime | NO | | NULL | | | modified_date | timestamp | NO | | CURRENT_TIMESTAMP | | | scrape_source | varchar(215) | YES | | NULL | | +---------------+--------------------------------------------------+------+-----+-------------------+----------------+ 18 rows in set (0.00 sec) mysql> describe categories -> ; +------------------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------------+------------------+------+-----+---------+----------------+ | category_id | int(10) unsigned | NO | PRI | NULL | auto_increment | | category_name | varchar(45) | NO | MUL | NULL | | | parent_id | int(10) unsigned | YES | MUL | NULL | | | category_type_id | int(10) unsigned | NO | | NULL | | +------------------+------------------+------+-----+---------+----------------+ 4 rows in set (0.00 sec) mysql> describe compatibilities -> ; +------------------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------------+------------------+------+-----+---------+----------------+ | compatibility_id | int(10) unsigned | NO | PRI | NULL | auto_increment | | name | varchar(45) | NO | | NULL | | | code_name | varchar(45) | NO | | NULL | | | description | varchar(128) | NO | | NULL | | | position | int(10) unsigned | NO | | NULL | | +------------------+------------------+------+-----+---------+----------------+ 5 rows in set (0.01 sec) mysql> describe distros -> ; +------------------+--------------------------------------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------------+--------------------------------------------------+------+-----+---------+----------------+ | id | int(10) unsigned | NO | PRI | NULL | auto_increment | | product_id | int(10) unsigned | NO | MUL | NULL | | | compatibility_id | int(10) unsigned | NO | MUL | NULL | | | user_id | int(10) unsigned | NO | | NULL | | | status | enum('pending','published','rejected','removed') | NO | | NULL | | | distro_type | enum('file','url') | NO | | NULL | | | version | varchar(150) | NO | | NULL | | | filename | varchar(50) | YES | | NULL | | | url | varchar(250) | YES | | NULL | | | virus | enum('READY','PASS','FAIL') | YES | | NULL | | | downloads | int(10) unsigned | NO | | 0 | | +------------------+--------------------------------------------------+------+-----+---------+----------------+ 11 rows in set (0.01 sec) mysql> describe downloads; +------------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------+------------------+------+-----+---------+----------------+ | id | int(10) unsigned | NO | PRI | NULL | auto_increment | | product_id | int(10) unsigned | NO | MUL | NULL | | | distro_id | int(10) unsigned | NO | MUL | NULL | | | user_id | int(10) unsigned | NO | MUL | NULL | | | ip_address | varchar(15) | NO | | NULL | | | date | datetime | NO | | NULL | | +------------+------------------+------+-----+---------+----------------+ 6 rows in set (0.01 sec) mysql> describe views -> ; +------------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------+------------------+------+-----+---------+----------------+ | id | int(10) unsigned | NO | PRI | NULL | auto_increment | | product_id | int(10) unsigned | NO | MUL | NULL | | | user_id | int(10) unsigned | NO | MUL | NULL | | | ip_address | varchar(15) | NO | | NULL | | | date | datetime | NO | | NULL | | +------------+------------------+------+-----+---------+----------------+ 5 rows in set (0.00 sec)

    Read the article

  • C#: Adding Functionality to 3rd Party Libraries With Extension Methods

    - by James Michael Hare
    Ever have one of those third party libraries that you love but it's missing that one feature or one piece of syntactical candy that would make it so much more useful?  This, I truly think, is one of the best uses of extension methods.  I began discussing extension methods in my last post (which you find here) where I expounded upon what I thought were some rules of thumb for using extension methods correctly.  As long as you keep in line with those (or similar) rules, they can often be useful for adding that little extra functionality or syntactical simplification for a library that you have little or no control over. Oh sure, you could take an open source project, download the source and add the methods you want, but then every time the library is updated you have to re-add your changes, which can be cumbersome and error prone.  And yes, you could possibly extend a class in a third party library and override features, but that's only if the class is not sealed, static, or constructed via factories. This is the perfect place to use an extension method!  And the best part is, you and your development team don't need to change anything!  Simply add the using for the namespace the extensions are in! So let's consider this example.  I love log4net!  Of all the logging libraries I've played with, it, to me, is one of the most flexible and configurable logging libraries and it performs great.  But this isn't about log4net, well, not directly.  So why would I want to add functionality?  Well, it's missing one thing I really want in the ILog interface: ability to specify logging level at runtime. For example, let's say I declare my ILog instance like so:     using log4net;     public class LoggingTest     {         private static readonly ILog _log = LogManager.GetLogger(typeof(LoggingTest));         ...     }     If you don't know log4net, the details aren't important, just to show that the field _log is the logger I have gotten from log4net. So now that I have that, I can log to it like so:     _log.Debug("This is the lowest level of logging and just for debugging output.");     _log.Info("This is an informational message.  Usual normal operation events.");     _log.Warn("This is a warning, something suspect but not necessarily wrong.");     _log.Error("This is an error, some sort of processing problem has happened.");     _log.Fatal("Fatals usually indicate the program is dying hideously."); And there's many flavors of each of these to log using string formatting, to log exceptions, etc.  But one thing there isn't: the ability to easily choose the logging level at runtime.  Notice, the logging levels above are chosen at compile time.  Of course, you could do some fun stuff with lambdas and wrap it, but that would obscure the simplicity of the interface.  And yes there is a Logger property you can dive down into where you can specify a Level, but the Level properties don't really match the ILog interface exactly and then you have to manually build a LogEvent and... well, it gets messy.  I want something simple and sexy so I can say:     _log.Log(someLevel, "This will be logged at whatever level I choose at runtime!");     Now, some purists out there might say you should always know what level you want to log at, and for the most part I agree with them.  For the most party the ILog interface satisfies 99% of my needs.  In fact, for most application logging yes you do always know the level you will be logging at, but when writing a utility class, you may not always know what level your user wants. I'll tell you, one of my favorite things is to write reusable components.  If I had my druthers I'd write framework libraries and shared components all day!  And being able to easily log at a runtime-chosen level is a big need for me.  After all, if I want my code to really be re-usable, I shouldn't force a user to deal with the logging level I choose. One of my favorite uses for this is in Interceptors -- I'll describe Interceptors in my next post and some of my favorites -- for now just know that an Interceptor wraps a class and allows you to add functionality to an existing method without changing it's signature.  At the risk of over-simplifying, it's a very generic implementation of the Decorator design pattern. So, say for example that you were writing an Interceptor that would time method calls and emit a log message if the method call execution time took beyond a certain threshold of time.  For instance, maybe if your database calls take more than 5,000 ms, you want to log a warning.  Or if a web method call takes over 1,000 ms, you want to log an informational message.  This would be an excellent use of logging at a generic level. So here was my personal wish-list of requirements for my task: Be able to determine if a runtime-specified logging level is enabled. Be able to log generically at a runtime-specified logging level. Have the same look-and-feel of the existing Debug, Info, Warn, Error, and Fatal calls.    Having the ability to also determine if logging for a level is on at runtime is also important so you don't spend time building a potentially expensive logging message if that level is off.  Consider an Interceptor that may log parameters on entrance to the method.  If you choose to log those parameter at DEBUG level and if DEBUG is not on, you don't want to spend the time serializing those parameters. Now, mine may not be the most elegant solution, but it performs really well since the enum I provide all uses contiguous values -- while it's never guaranteed, contiguous switch values usually get compiled into a jump table in IL which is VERY performant - O(1) - but even if it doesn't, it's still so fast you'd never need to worry about it. So first, I need a way to let users pass in logging levels.  Sure, log4net has a Level class, but it's a class with static members and plus it provides way too many options compared to ILog interface itself -- and wouldn't perform as well in my level-check -- so I define an enum like below.     namespace Shared.Logging.Extensions     {         // enum to specify available logging levels.         public enum LoggingLevel         {             Debug,             Informational,             Warning,             Error,             Fatal         }     } Now, once I have this, writing the extension methods I need is trivial.  Once again, I would typically /// comment fully, but I'm eliminating for blogging brevity:     namespace Shared.Logging.Extensions     {         // the extension methods to add functionality to the ILog interface         public static class LogExtensions         {             // Determines if logging is enabled at a given level.             public static bool IsLogEnabled(this ILog logger, LoggingLevel level)             {                 switch (level)                 {                     case LoggingLevel.Debug:                         return logger.IsDebugEnabled;                     case LoggingLevel.Informational:                         return logger.IsInfoEnabled;                     case LoggingLevel.Warning:                         return logger.IsWarnEnabled;                     case LoggingLevel.Error:                         return logger.IsErrorEnabled;                     case LoggingLevel.Fatal:                         return logger.IsFatalEnabled;                 }                                 return false;             }             // Logs a simple message - uses same signature except adds LoggingLevel             public static void Log(this ILog logger, LoggingLevel level, object message)             {                 switch (level)                 {                     case LoggingLevel.Debug:                         logger.Debug(message);                         break;                     case LoggingLevel.Informational:                         logger.Info(message);                         break;                     case LoggingLevel.Warning:                         logger.Warn(message);                         break;                     case LoggingLevel.Error:                         logger.Error(message);                         break;                     case LoggingLevel.Fatal:                         logger.Fatal(message);                         break;                 }             }             // Logs a message and exception to the log at specified level.             public static void Log(this ILog logger, LoggingLevel level, object message, Exception exception)             {                 switch (level)                 {                     case LoggingLevel.Debug:                         logger.Debug(message, exception);                         break;                     case LoggingLevel.Informational:                         logger.Info(message, exception);                         break;                     case LoggingLevel.Warning:                         logger.Warn(message, exception);                         break;                     case LoggingLevel.Error:                         logger.Error(message, exception);                         break;                     case LoggingLevel.Fatal:                         logger.Fatal(message, exception);                         break;                 }             }             // Logs a formatted message to the log at the specified level.              public static void LogFormat(this ILog logger, LoggingLevel level, string format,                                          params object[] args)             {                 switch (level)                 {                     case LoggingLevel.Debug:                         logger.DebugFormat(format, args);                         break;                     case LoggingLevel.Informational:                         logger.InfoFormat(format, args);                         break;                     case LoggingLevel.Warning:                         logger.WarnFormat(format, args);                         break;                     case LoggingLevel.Error:                         logger.ErrorFormat(format, args);                         break;                     case LoggingLevel.Fatal:                         logger.FatalFormat(format, args);                         break;                 }             }         }     } So there it is!  I didn't have to modify the log4net source code, so if a new version comes out, i can just add the new assembly with no changes.  I didn't have to subclass and worry about developers not calling my sub-class instead of the original.  I simply provide the extension methods and it's as if the long lost extension methods were always a part of the ILog interface! Consider a very contrived example using the original interface:     // using the original ILog interface     public class DatabaseUtility     {         private static readonly ILog _log = LogManager.Create(typeof(DatabaseUtility));                 // some theoretical method to time         IDataReader Execute(string statement)         {             var timer = new System.Diagnostics.Stopwatch();                         // do DB magic                                    // this is hard-coded to warn, if want to change at runtime tough luck!             if (timer.ElapsedMilliseconds > 5000 && _log.IsWarnEnabled)             {                 _log.WarnFormat("Statement {0} took too long to execute.", statement);             }             ...         }     }     Now consider this alternate call where the logging level could be perhaps a property of the class          // using the original ILog interface     public class DatabaseUtility     {         private static readonly ILog _log = LogManager.Create(typeof(DatabaseUtility));                 // allow logging level to be specified by user of class instead         public LoggingLevel ThresholdLogLevel { get; set; }                 // some theoretical method to time         IDataReader Execute(string statement)         {             var timer = new System.Diagnostics.Stopwatch();                         // do DB magic                                    // this is hard-coded to warn, if want to change at runtime tough luck!             if (timer.ElapsedMilliseconds > 5000 && _log.IsLogEnabled(ThresholdLogLevel))             {                 _log.LogFormat(ThresholdLogLevel, "Statement {0} took too long to execute.",                     statement);             }             ...         }     } Next time, I'll show one of my favorite uses for these extension methods in an Interceptor.

    Read the article

  • Guidance in naming awkward objects?

    - by GlenH7
    I'm modeling a chemical system, and I'm having problems with naming my objects within an enum. I'm not sure if I should use: the atomic formula the chemical name an abbreviated chemical name. For example, sulfuric acid is H2SO4 and hydrochloric acid is HCl. With those two, I would probably just use the atomic formula as they are reasonably common. However, I have others like sodium hexafluorosilicate which is Na2SiF6. In that example, the atomic formula isn't as obvious (to me) but the chemical name is hideously long: myEnum.SodiumHexaFluoroSilicate. I'm not sure how I would be able to safely come up with an abbreviated chemical name that would have a consistent naming pattern. From a maintenance point of view, which of the options would you prefer to see and why? Audience for the code will be just programmers, not chemists. If that guides the particulars: I'm using C#; I'm starting with 10 - 20 compounds and would have at most 100 compounds. The enum is to facilitate common calculations - the equation is the same for all compounds but you insert a property of the compound to complete the equation.

    Read the article

  • Guidance in naming awkward domain-specific objects?

    - by GlenH7
    I'm modeling a chemical system, and I'm having problems with naming my objects within an enum. I'm not sure if I should use: the atomic formula the chemical name an abbreviated chemical name. For example, sulfuric acid is H2SO4 and hydrochloric acid is HCl. With those two, I would probably just use the atomic formula as they are reasonably common. However, I have others like sodium hexafluorosilicate which is Na2SiF6. In that example, the atomic formula isn't as obvious (to me) but the chemical name is hideously long: myEnum.SodiumHexaFluoroSilicate. I'm not sure how I would be able to safely come up with an abbreviated chemical name that would have a consistent naming pattern. From a maintenance point of view, which of the options would you prefer to see and why? Some details from comments on this question: Audience for the code will be just programmers, not chemists. I'm using C#, but I think this question is more interesting when ignoring the implementation language I'm starting with 10 - 20 compounds and would have at most 100 compounds. The enum is to facilitate common calculations - the equation is the same for all compounds but you insert a property of the compound to complete the equation. For example, Molar mass (in g/mol) is used when calculating the number of moles from a mass (in grams) of the compound. Another example of a common calculation is the Ideal Gas Law and its use of the Specific Gas Constant

    Read the article

< Previous Page | 17 18 19 20 21 22 23 24 25 26 27 28  | Next Page >