Search Results

Search found 177 results on 8 pages for 'emp'.

Page 7/8 | < Previous Page | 3 4 5 6 7 8  | Next Page >

  • Build comma seperated string from the struct in C#

    - by acadia
    Hello, I have the following struct in C# class public struct Employee { public const string EMPID = "EMP_ID"; public const string FName = "FIRST_NAME"; public const string LNAME = "LAST_NAME"; public const string DEPTID = "DEPT_ID"; } Is there an easy way to build a string as follows const string mainquery="INSERT INTO EMP(EMP_ID,FIRST_NAME,LAST_NAME,DEPT_ID) VALUES(:EMP_ID,:FIRST_NAME,:LAST_NAME,:DEPT_ID)" Instead of doing as follows and then concatenating it. const string EMP_COLS= EMPLOYEE.EMPID + "," + EMPLOYEE.FNAME + "," + EMPLOYEE.LNAME + "," + EMPLOYEE.DEPTID; const string EMP_Values= EMPLOYEE.EMPID + ":" + EMPLOYEE.FNAME + ":" + EMPLOYEE.LNAME + ":" + EMPLOYEE.DEPTID;

    Read the article

  • how to filter in sql

    - by user3634746
    good day i have a database containing time in and time out and i want to filter all the record of the employees time in and time out. here is my sample db using php and mysql PersonalId LogCount LogDate LogType LogKind 2 1 2014-04-09 12:42:24 0 0 2 1 2014-04-10 12:43:53 1 0 2 1 2014-04-11 02:17:39 0 0 2 2 2014-04-09 12:42:48 1 0 3 2 2014-04-10 12:44:14 0 0 3 2 2014-04-11 02:48:54 1 0 3 3 2014-04-09 12:43:23 0 0 3 3 2014-04-09 12:43:23 1 0 0 in log type is =login 1 in log type is =login this will be the format emp id IN OUT HOURS 2 6/2/2014 8:15 6/2/2014 17:00 7.25 2 6/2/2014 8:15 6/2/2014 17:00 7.25 thanks for your help

    Read the article

  • How to set conditional activation to taskflows?

    - by shantala.sankeshwar(at)oracle.com
    This article describes implementing conditional activation to taskflows.Use Case Description Suppose we have a taskflow dropped as region on a page & this region is enclosed in a popup .By default when the page is loaded the respective region also gets loaded.Hence a region model needs to provide a viewId whenever one is requested.  A consequence of this is the TaskFlowRegionModel always has to initialize its task flow and execute the task flow's default activity in order to determine a viewId, even if the region is not visible on the page.This can lead to unnecessary performance overhead of executing task flow to generate viewIds for regions that are never visible. In order to increase the performance,we need to set the taskflow bindings activation property to 'conditional'.Below described is a simple usecase that shows how exactly we can set the conditional activations to taskflow bindings.Steps:1.Create an ADF Fusion web ApplicationView image 2.Create Business components for Emp tableView image3.Create a view criteria where deptno=:some_bind_variableView image4.Generate EmpViewImpl.java file & write the below code.Then expose this to client interface.    public void filterEmpRecords(Number deptNo){            // Code to filter the deptnos         ensureVariableManager().setVariableValue("some_bind_variable",  deptNo);        this.applyViewCriteria(this.getViewCriteria("EmpViewCriteria"));        this.executeQuery();       }5.Create an ADF Taskflow with page fragements & drop the above method on the taskflow6.Also drop the view activity(showEmp.jsff) .Define control flow case from the above method activity to the view activity.Set the method activity as default activityView image7.Create  main.jspx page & drop the above taskflow as region on this pageView image8.Surround the region with the dialog & surround the dialog with the popup(id is Popup1)9.Drop the commandButton on the above page & insert af:showPopupBehavior inside the commandButton:<af:commandButton text="show popup" id="cb1"><af:showPopupBehavior popupId="::Popup1"/></af:commandButton>10.Now if we execute this main page ,we will notice that the method action gets called even before the popup is launched.We can avoid this this by setting the activation property of the taskflow to conditional11.Goto the bindings of the above main page & select the taskflow binding ,set its activation property to 'conditional' & active property to Boolean value #{Somebean.popupVisible}.By default its value should be false.View image12.We need to set the above Boolean value to true only when the popup is launched.This can be achieved by inserting setPropertyListener inside the popup:<af:setPropertyListener from="true" to="#{Somebean.popupVisible}" type="popupFetch"/>13.Now if we run the page,we will notice that the method action is not called & only when we click on 'show popup' button the method action gets called.

    Read the article

  • SQL Developer: Why Do You Require Semicolons When Executing SQL in the Worksheet?

    - by thatjeffsmith
    There are many database tools out there that support Oracle database. Oracle SQL Developer just happens to be the one that is produced and shipped by the same folks that bring you the database product. Several other 3rd party tools out there allow you to have a collection of SQL statements in their editor and execute them without requiring a statement delimiter (usually a semicolon.) Let’s look at a quick example: select * from scott.emp select * from hr.employees delete from HR_COPY.BEER where HR_COPY.BEER.STATE like '%West Virginia% In some tools, you can simply place your cursor on say the 2nd statement and ask to execute that statement. The tool assumes that the blank line between it and the next statement, a DELETE, serves as a statement delimiter. This is not bad in and of itself. However, it is very important to understand how your tools work. If you were to try the same trick by running the delete statement, it would empty my entire BEER table instead of just trimming out the breweries from my home state. SQL Developer only executes what you ask it to execute You can paste this same code into SQL Developer and run it without problems and without having to add semicolons to your statements. Highlight what you want executed, and hit Ctrl-Enter If you don’t highlight the text, here’s what you’ll see: See the statement at the cursor vs what SQL Developer actually executed? The parser looks for a query and keeps going until the statement is terminated with a semicolon – UNLESS it’s highlighted, then it assumes you only want to execute what is highlighted. In both cases you are being explicit with what is being sent to the database. Again, there’s not necessarily a ‘right’ or ‘wrong’ debate here. What you need to be aware of is the differences and to learn new workflows if you are moving from other database tools to Oracle SQL Developer. I say, when in doubt, back away from the tool, especially if you’re in production. Oh, and to answer the original question… Because we’re trying to emulate SQL*Plus behavior. You end statements in SQL*Plus with delimiters, and the default delimiter is a semicolon.

    Read the article

  • Challenge 19 – An Explanation of a Query

    - by Dave Ballantyne
    I have received a number of requests for an explanation of my winning query of TSQL Challenge 19. This involved traversing a hierarchy of employees and rolling a count of orders from subordinates up to superiors. The first concept I shall address is the hierarchyId , which is constructed within the CTE called cteTree.   cteTree is a recursive cte that will expand the parent-child hierarchy of the personnel in the table @emp.  One useful feature with a recursive cte is that data can be ‘passed’ from the parent to the child data.  The hierarchyId column is similar to the hierarchyId data type that was introduced in SQL Server 2008 and represents the position of the person within the organisation. Let us start with a simplistic example Albert manages Bob and Eddie.  Bob manages Carl and Dave. The hierarchyId will represent each person’s position in this relationship in a single field.  In this simple example we could append the userID together into a varchar field as detailed below. This will enable us to select a branch of the tree by filtering using Where hierarchyId  ‘1,2%’ to select Bob and all his subordinates.  Naturally, this is not comprehensive enough to provide a full solution, but as opposed to concatenating the Id’s together into a varchar datatyped column, we can apply the same theory to a varbinary.  By CASTing the ID’s into a datatype of varbinary(4) ,4 is used as 4 bytes of data are used to store an integer and building a hierarchyId  from those.  For example: The important point to bear in mind for later in the query is that the binary data generated is 'byte order comparable'. ie We can ORDER a dataset with it and the resulting data, will be in the order required. Now, would probably be a good time to download the example file and, after the cte ‘cteTree’, uncomment the line ‘select * from cteTree’.  Mark this and all prior code and execute.  This will show you how this theory directly relates to the actual challenge data.  The only deviation from the above, is that instead of using the ID of an employee, I have used the row_number() ranking function to order each level by LastName,Firstname.  This enables me to order by the HierarchyId in the final result set so that the result set is in the required order. Your output should be something like the below.  Notice also the ‘Level’ Column that contains the depth that the employee is within the tree.  I would encourage you to ‘play’ with the query, change the order in the row_number() or the length of the cast in the hierarchyId to see how that effects the outcome.  The next cte, ‘cteTreeWithOrderCount’, is a join between cteTree and the @ord table, and COUNT’s the number of orders per employee.  A LEFT JOIN is employed here to account for the occasion where an employee has made no sales.   Executing a ‘Select * from cteTreeWithOrderCount’ will return the result set as below.  The order here is unimportant as this is only a staging point of the data and only the final result set in a cte chain needs an Order by clause, unless TOP is utilised. cteExplode joins the above result set to the tally table (Nums) for Level Occurances.  So, if level is 2 then 2 rows are required.  This is done to expand the dataset, to create a new column (PathInc), which is the (n+1) integers contained within the heirarchyid.  For example, with the data for Robert King as given above, the below 3 rows will be returned. From this you can see that the pathinc column now contains the values for Andrew Fuller and Steven Buchanan who are Robert King’s superiors within the tree.    Finally cteSumUp, sums the orders for each person and their subordinates using the PathInc generated above, and the final select does the final simple mathematics and filters to restrict the result set to only the ‘original’ row per employee.

    Read the article

  • export web page data to excel using javascript [on hold]

    - by Sreevani sri
    I have created web page using html.When i clicked on submit button it will export to excel. using javascript i wnt to export thadt data to excel. my html code is 1. Please give your Name:<input type="text" name="Name" /><br /> 2. Area where you reside:<input type="text" name="Res" /><br /> 3. Specify your age group<br /> (a)15-25<input type="text" name="age" /> (b)26-35<input type="text" name="age" /> (c)36-45<input type="text" name="age" /> (d) Above 46<input type="text" name="age" /><br /> 4. Specify your occupation<br /> (a) Student<input type="checkbox" name="occ" value="student" /> (b) Home maker<input type="checkbox" name="occ" value="home" /> (c) Employee<input type="checkbox" name="occ" value="emp" /> (d) Businesswoman <input type="checkbox" name="occ" value="buss" /> (e) Retired<input type="checkbox" name="occ" value="retired" /> (f) others (please specify)<input type="text" name="others" /><br /> 5. Specify the nature of your family<br /> (a) Joint family<input type="checkbox" name="family" value="jfamily" /> (b) Nuclear family<input type="checkbox" name="family" value="nfamily" /><br /> 6. Please give the Number of female members in your family and their average age approximately<br /> Members Age 1 2 3 4 5<br /> 8. Please give your highest level of education (a)SSC or below<input type="checkbox" name="edu" value="ssc" /> (b) Intermediate<input type="checkbox" name="edu" value="int" /> (c) Diploma <input type="checkbox" name="edu" value="dip" /> (d)UG degree <input type="checkbox" name="edu" value="deg" /> (e) PG <input type="checkbox" name="edu" value="pg" /> (g) Doctorial degree<input type="checkbox" name="edu" value="doc" /><br /> 9. Specify your monthly income approximately in RS <input type="text" name="income" /><br /> 10. Specify your time spent in making a purchase decision at the outlet<br /> (a)0-15 min <input type="checkbox" name="dis" value="0-15 min" /> (b)16-30 min <input type="checkbox" name="dis" value="16-30 min" /> (c) 30-45 min<input type="checkbox" name="dis" value="30-45 min" /> (d) 46-60 min<input type="checkbox" name="dis" value="46-60 min" /><br /> <input type="submit" onclick="exportToExcel()" value="Submit" /> </div> </form>

    Read the article

  • Book Review: Oracle ADF 11gR2 Development Beginner's Guide

    - by Grant Ronald
    Packt Publishing asked me to review Oracle ADF 11gR2 Development Beginner's Guide by Vinod Krishnan, so on a couple of long flights I managed to get through the book in a couple of sittings. One point to make clear before I go into the review.  Having authored "The Quick Start Guide to Fusion Development: JDeveloper and Oracle ADF", I've written a book which covers the same topic/beginner level.  I also think that its worth stating up front that I applaud anyone who has gone  through the effort of writing a technical book. So well done Vinod.  But on to the review: The book itself is a good break down of topic areas.  Vinod starts with a quick tour around the IDE, which is an important step given all the work you do will be through the IDE.  The book then goes through the general path that I tend to always teach: a quick overview demo, ADF BC, validation, binding, UI, task flows and then the various "add on" topics like security, MDS and advanced topics.  So it covers the right topics in, IMO, the right order.  I also think the writing style flows nicely as well - Its a relatively easy book to read, it doesn't get too formal and the "Have a go hero" hands on sections will be useful for many. That said, I did pick out a number of styles/themes to the writing that I found went against the idea of a beginners guide.  For example, in writing my book, I tried to carefully avoid talking about topics not yet covered or not yet relevant at that point in someone's learning.  So, if I was a new ADF developer reading this book, did I really need to know about ADFBindingFilter and DataBindings.cpx file on page 58 - I've only just learned how to do a drag and drop simple application so showing me XML configuration files relevant to JSF/ADF lifecycle is probably going to scare me off! I found this in a couple of places, for example, the security chapter starts on page 219 but by page 222 (and most of the preceding pages are hands-on steps) we're diving into the web.xml, weblogic.xml, adf-config.xml, jsp-config.xml and jazn-data.xml.  Don't get me wrong, I'm not saying you shouldn't know this, but I feel you have to get people on a strong grounding of the concepts before showing them implementation files.  If having just learned what ADF Security is will "The initialization parameter remove.anonymous.role is set to false for the JpsFilter filter as this filter is the first filter defined in the file" really going to help me? The other theme I found which I felt didn't work was that a couple of the chapters descended into a reference guide.  For example page 159 onwards basically lists UI components and their properties.  And page 87 onwards list the attributes of ADF BC in pretty much the same way as the on line help or developer guide, and I've a personal aversion to any sort of help that says pretty much what the attribute name is e.g. "Precision Rule: this option is used to set a strict precision rule", or "Property Set: this is the property set that has to be applied to the attribute". Hmmm, I think I could have worked that out myself, what I would want to know in a beginners guide are what are these for, what might I use them for...and if I don't need to use them to create an emp/dept example them maybe it’s better to leave them out. All that said, would the book help me - yes it would.  It’s obvious that Vinod knows ADF and his style is relatively easy going and the book covers all that it has to, but I think the book could have done a better job in the educational side of guiding beginners.

    Read the article

  • Delete duplicate records from a SQL table without a primary key

    - by Shyju
    I have the below table with the below records in it create table employee ( EmpId number, EmpName varchar2(10), EmpSSN varchar2(11) ); insert into employee values(1, 'Jack', '555-55-5555'); insert into employee values (2, 'Joe', '555-56-5555'); insert into employee values (3, 'Fred', '555-57-5555'); insert into employee values (4, 'Mike', '555-58-5555'); insert into employee values (5, 'Cathy', '555-59-5555'); insert into employee values (6, 'Lisa', '555-70-5555'); insert into employee values (1, 'Jack', '555-55-5555'); insert into employee values (4, 'Mike', '555-58-5555'); insert into employee values (5, 'Cathy', '555-59-5555'); insert into employee values (6 ,'Lisa', '555-70-5555'); insert into employee values (5, 'Cathy', '555-59-5555'); insert into employee values (6, 'Lisa', '555-70-5555'); I dont have any primary key in this table .But i have the above records in my table already. I want to remove the duplicate records which has the same value in EmpId and EmpSSN fields. Ex : Emp id 5 Can any one help me to frame a query to delete those duplicate records Thanks in advance

    Read the article

  • Using datetime float representation as primary key

    - by devanalyst
    From my experience I have learn that using an surrogate INT data type column as primary key esp. an IDENTITY key column offers better performance than using GUID or char/varchar data type column as primary key. I try to use IDENTITY key as primary key wherever possible. But recently I came across a schema where the tables were horizontally partitioned and were managed via a Partitioned view. So the tables could not have an IDENTITY column since that would make the Partitioned View non updatable. One work around for this was to create a dummy 'keygenerator' table with an identity column to generate IDs for primary key. But this would mean having a 'keygenerator' table for each of the Partitioned View. My next thought was to use float as a primary key. The reason is the following key algorithm that I devised DECLARE @KEY FLOAT SET @KEY = CONVERT(FLOAT,GETDATE())/100000.0 SET @KEY = @EMP_ID + @KEY Heres how it works. CONVERT(FLOAT,GETDATE()) gives float representation of current datetime since internally all datetime are represented by SQL as a float value. CONVERT(FLOAT,GETDATE())/100000.0 converts the float representation into complete decimal value i.e. all digits are pushed to right side of ".". @KEY = @EMP_ID + @KEY adds the Employee ID which is an integer to this decimal value. The logic is that the Employee ID is guaranteed to be unique across sessions since an employee cannot connect to an application more than once at the same time. And for the same employee each time a key will be generated the current datetime will be unique. In all an unique key across all employee sessions and across time. So for Emp Ids 11 and 12, I have key values like 12.40046693321566357, 11.40046693542361111 But my concern whether float data type as primary key offer benefits compared to choosing GUID or char/varchar as primary keys. Also important thing is because of partitioning the float column is going to be part of a composite key.

    Read the article

  • ModalPopupExtender + ASP.NET AJAX: Can't page grid

    - by Alex
    I'm trying to page and sort my datagrid wich is inside a modalpopupextender but I can't page it in any way, already tried with , put the updatepanel inside, outside, in the middle (loL) and it does NOT work. modal popup does not get closed but the grid just dissapear. Code: Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then BindData() End If End Sub Private Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click SqlServerDS.SelectCommand = "SELECT * FROM emp WHERE name LIKE '%" & txtSearchName.Text & "%'" BindData() End Sub Private Sub BindData() grdSearch.DataSource = SqlServerDS grdSearch.DataBind() End Sub Private Sub grdBuscaPaciente_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles grdSearch.PageIndexChanging grdSearch.PageIndex = e.NewPageIndex BindData() End Sub Inside the Designer, this is the code h: <modalpopupextender> </modalpopupextender> <panel> <updatepanel> <gridview> </gridview> </updatepanel> </panel>

    Read the article

  • Can this extension method be improved?

    - by Newbie
    I have the following extension method public static class ListExtensions { public static IEnumerable<T> Search<T>(this ICollection<T> collection, string stringToSearch) { foreach (T t in collection) { Type k = t.GetType(); PropertyInfo pi = k.GetProperty("Name"); if (pi.GetValue(t, null).Equals(stringToSearch)) { yield return t; } } } } What it does is by using reflection, it finds the name property and then filteres the record from the collection based on the matching string. This method is being called as List<FactorClass> listFC = new List<FactorClass>(); listFC.Add(new FactorClass { Name = "BKP", FactorValue="Book to price",IsGlobal =false }); listFC.Add(new FactorClass { Name = "YLD", FactorValue = "Dividend yield", IsGlobal = false }); listFC.Add(new FactorClass { Name = "EPM", FactorValue = "emp", IsGlobal = false }); listFC.Add(new FactorClass { Name = "SE", FactorValue = "something else", IsGlobal = false }); List<FactorClass> listFC1 = listFC.Search("BKP").ToList(); It is working fine. But a closer look into the extension method will reveal that Type k = t.GetType(); PropertyInfo pi = k.GetProperty("Name"); is actually inside a foreach loop which is actually not needed. I think we can take it outside the loop. But how? PLease help. (C#3.0)

    Read the article

  • C# -Fluent interface implementation Help

    - by nettguy
    I am implementing the following piece of code using Fluent Interface design in C# 3.0. The code is working fine. public interface ITrainable { ITrainable AddSkill(string _skill); } public interface ISearchSkill { ISearchSkill SearchSkill(SoftwareEngineer emp,string[] _skills); } public abstract class Person { public Person(){} protected string Name { get; set; } } public class SoftwareEngineer:Person,ITrainable { protected internal List<string> skillSet { get; set; } public SoftwareEngineer() { } public SoftwareEngineer(string name) { Name=name; skillSet = new List<string>(); } public ITrainable AddSkill(string _skill) { skillSet.Add(_skill); return this; } } public class HRExecutive :Person,ISearchSkill { SoftwareEngineer _employee; public HRExecutive() { _employee=new SoftwareEngineer(); } public ISearchSkill SearchSkill(SoftwareEngineer _employee,string[] skills) { this._employee= _employee; foreach (string _skill in skills) { if (_employee.skillSet.Contains(_skill)) { Console.WriteLine(Name + " is trained on " + _skill); } else { Console.WriteLine(Name + " is not trained on " + _skill); } } return this; } } Execution SoftwareEngineer emp1 = new SoftwareEngineer("JonSkeet"); emp1.AddSkill("java").AddSkill("C#").AddSkill("F#"); HRExecutive hr = new HRExecutive(); hr.SearchSkill(emp1, new string[] { "java", "C#" }). SearchSkill(emp1, new string[] { "Oracle", "F#" }); Question : I don't want the skillSet of SoftwareEngineer being accessed by some XXX class.It could be accessed by limited classes.But protected internal List<string> skillSet { get; set; } is the only option (i think) i can declare in order to access the skillSet from HRExecutive.If i do so other XXX class can still access it. How to rewrite the code to prevent it?

    Read the article

  • Handling Denormalized Schema with Eclipselink

    - by iamrohitbanga
    Hello All I have a denormalized table containing employee information. The fields are employee id, name and department name. The primary key is a composite one consisting of all three fields. An employee can belong to multiple departments. I want to read/write the objects in the table using the Eclipselink Dynamic Persistence API (which is infact a wrapper on top of JPA descriptors etc.). Example Data: 1 e1 dep1 2 e1 dep2 3 e2 dep1 4 e2 dep3 5 e3 dep1 5 e3 dep2 5 e3 dep3 A normal ReadAllQuery (select query) on the table returns a DynamicEntity corresponding to each row in the table. However I want to club all entities based on the emp id and return all the departments he belongs to as a list. I can merge the entities after retrieving them but if I can use some Eclipselink feature out of the box then it would be better. One way to do the read is the following: I create two dynamic types corresponding to employee: Having id,name as the primary key Having id, department as the primary key, I create a OneToManyMapping from the first type to the second one. Then when I query the first type it does return the departments to which employee belongs as a list of DynamicEntity of the second type. This satisfies the read scenario. Is there a better way of doing this? Is this inherently supported by Eclipselink or JPA? I cannot get the same dynamic type configuration working for the write scenario. This is because when I write the changes using the writeObject method of UnitOfWork, it generates insert queries which enter the following entries in the table id name department 102 emp_102 102 st 102 dep_102 102 dep_102 102 dep_102 instead of: id name department 102 emp_102 st 102 emp_102 dep_102 102 emp_102 dep_102 102 emp_102 dep_102 Is there any way I can get write to work with this schema using eclipselink? I want to avoid doing the heavy lifting of merging the rows for such a denormalized schema or generating each row before doing a write. Is there no clean way of doing this using Eclipselink or JPA? Thanks in Advance.

    Read the article

  • Search field based on multiple parameter

    - by Manoj Wadhwani
    Can anybody modify this , when i insert Emp. name it go to first search and it does not check other paramete could you plz modify this sp for exact search on based on parameter. --select * from Training_TRNS --USP_SearchEmployee '','2008-04-18 00:00:00.000','','','','','' alter Procedure USP_SearchEmployee @EmpName varchar(100)=null, @DateFrom varchar(100)=null, @DateTo varchar(100)=null, @CourseName varchar(100)=null, @JobFunction varchar(100)=null, @Region varchar(100)=null, @Status varchar(100)=null AS BEGIN if (@EmpName!='' and @EmpName is not null) BEGIN select EmpName,convert(varchar,DueDate,101) as DueDate,SpeCourse_ID as CourseName, EmpJobFunction as JOBFunction,EmpRegion as Region,Status from Training_TRNS where EmpName like '%'+@EmpName+'%' END ELSE IF (@CourseName!='' and @CourseName is not null) BEGIN select EmpName,convert(varchar,DueDate,101) as DueDate,SpeCourse_ID as CourseName, EmpJobFunction as JOBFunction,EmpRegion as Region,Status from Training_TRNS where SpeCourse_ID like '%'+@CourseName+'%' END ELSE IF (@JobFunction!='' and @JobFunction is not null) BEGIN select EmpName,convert(varchar,DueDate,101) as DueDate,SpeCourse_ID as CourseName, EmpJobFunction as JOBFunction,EmpRegion as Region,Status from Training_TRNS where EmpJobFunction like '%'+@JobFunction+'%' END ELSE IF (@Region!='' and @Region is not null) BEGIN select EmpName,convert(varchar,DueDate,101) as DueDate,SpeCourse_ID as CourseName, EmpJobFunction as JOBFunction,EmpRegion as Region,Status from Training_TRNS where EmpRegion like '%'+@Region+'%' END ELSE IF (@Status!='' and @Status is not null) BEGIN select EmpName,convert(varchar,DueDate,101) as DueDate,SpeCourse_ID as CourseName, EmpJobFunction as JOBFunction,EmpRegion as Region,Status from Training_TRNS where Status like '%'+@Status+'%' END ELSE IF (@DateFrom!='' and @DateFrom is not null) BEGIN select EmpName,convert(varchar,DueDate,101) as DueDate,SpeCourse_ID as CourseName, EmpJobFunction as JOBFunction,EmpRegion as Region,Status from Training_TRNS where convert(varchar,DueDate,101) like '%'+convert(varchar,@DateFrom,101)+'%' END Else BEGIN select EmpName,convert(varchar,DueDate,101) as DueDate,SpeCourse_ID as CourseName, EmpJobFunction as JOBFunction,EmpRegion as Region,Status from Training_TRNS END END

    Read the article

  • Sort ranges in an array in google apps script

    - by user1637113
    I have a timesheet spreadsheet for our company and I need to sort the employees by each timesheet block (15 rows by 20 columns). I have the following code which I had help with, but the array quits sorting once it comes to a block without an employee name (I would like these to be shuffled to the bottom). Another complication I am having is there are numerous formulas in these cells and when I run it as is, it removes them. I would like to keep these intact if at all possible. Here's the code: function sortSections() { var activeSheet = SpreadsheetApp.getActiveSheet(); //SETTINGS var sheetName = activeSheet.getSheetName(); //name of sheet to be sorted var headerRows = 53; //number of header rows var pageHeaderRows = 5; //page totals to top of next emp section var sortColumn = 11; //index of column to be sorted by; 1 = column A var pageSize = 65; var sectionSize = 15; //number of rows in each section var col = sortColumn-1; var sheet = SpreadsheetApp.getActive().getSheetByName(sheetName); var data = sheet.getRange(headerRows+1, 1, sheet.getMaxRows()-headerRows, sheet.getLastColumn()).getValues(); var data3d = []; var dataLength = data.length/sectionSize; for (var i = 0; i < dataLength; i++) { data3d[i] = data.splice(0, sectionSize); } data3d.sort(function(a,b){return(((a[0][col]<b[0][col])&&a[0][col])?-1:((a[0][col]>b[0][col])?1:0))}); var sortedData = []; for (var k in data3d) { for (var l in data3d[k]) { sortedData.push(data3d[k][l]); } } sheet.getRange(headerRows+1, 1, sortedData.length, sortedData[0].length).setValues(sortedData);

    Read the article

  • Can this extension method be improve

    - by Newbie
    I have the following extension method public static class ListExtensions { public static IEnumerable<T> Search<T>(this ICollection<T> collection, string stringToSearch) { foreach (T t in collection) { Type k = t.GetType(); PropertyInfo pi = k.GetProperty("Name"); if (pi.GetValue(t, null).Equals(stringToSearch)) { yield return t; } } } } What it does is by using reflection, it finds the name property and then filteres the record from the collection based on the matching string. This method is being called as List<FactorClass> listFC = new List<FactorClass>(); listFC.Add(new FactorClass { Name = "BKP", FactorValue="Book to price",IsGlobal =false }); listFC.Add(new FactorClass { Name = "YLD", FactorValue = "Dividend yield", IsGlobal = false }); listFC.Add(new FactorClass { Name = "EPM", FactorValue = "emp", IsGlobal = false }); listFC.Add(new FactorClass { Name = "SE", FactorValue = "something else", IsGlobal = false }); List<FactorClass> listFC1 = listFC.Search("BKP").ToList(); It is working fine. But a closer look into the extension method will reveal that Type k = t.GetType(); PropertyInfo pi = k.GetProperty("Name"); is actually inside a foreach loop which is actually not needed. I think we can take it outside the loop. But how? PLease help. (C#3.0)

    Read the article

  • how to create following Java applicatin? [on hold]

    - by Tushar Bichwe
    Write a JAVA program which performs the following listed operations: A. Create a package named MyEmpPackage which consists of following classes A class named Employee which stores information like the Emp number, first name, middle name, last name, address, designation and salary. The class should also contain appropriate get and set methods. 05 A class named AddEmployeeFrame which displays a frame consisting of appropriate controls to enter the details of a Employee and store these details in the Employee class object. The frame should also have three buttons with the caption as “Add Record” and “Delete Record” and “Exit”. 10 A class named MyCustomListener which should work as a user – defined event listener to handle required events as mentioned in following points. 05 B When the “Add Record” button is clicked, the dialog box should be appeared with asking the user “Do you really want to add record in the file”. If the user selects Yes than the record should be saved in the file. 10 When the “Exit” button is clicked, the frame should be closed. 10 [Note: Use the MyCustomListener class only to handle the appropriate events] C The “Delete Record” button should open a new frame which should take input of delete criteria using a radio button. The radio button should provide facility to delete on basis of first name, middle name or last name. 10 The new frame should also have a text box to input the delete criteria value. 10 The record should be deleted from the file and a message dialog should appear with the message that “Record is successfully Deleted”. 10 [Note: Use the MyCustomListener class only to handle the appropriate events] D Provide proper error messages and perform appropriate exceptions where ever required in all the classes 10

    Read the article

  • Dynamic Data Connections

    - by Tim Dexter
    I have had a long running email thread running between Dan and David over at Valspar and myself. They have built some impressive connectivity between their in house apps and BIP using web services. The crux of their problem has been that they have multiple databases that need the same report executed against them. Not such an unusual request as I have spoken to two customers in the last month with the same situation. Of course, you could create a report against each data connection and just run or call the appropriate report. Not too bad if you have two or three data connections but more than that and it becomes a maintenance nightmare having to update queries or layouts. Ideally you want to have just a single report definition on the BIP server and to dynamically set the connection to be used at runtime based on the user or system that the user is in. A quick bit of digging and help from Shinji on the development team and I had an answer. Rather embarassingly, the solution has been around since the Oct 2010 rollup patch last year. Still, I grabbed the latest Jan 2011 patch - check out Note 797057.1 for the latest available patches. Once installed, I used the best web service testing tool I have yet to come across - SoapUI. Just point it at the WSDL and you can check out the available services and their parameters and then test them too. The XML packet has a new dynamic data source entry. You can set you own custom JDBC connection or just specify an existing data source name thats defined on the server. <pub:runReport> <pub:reportRequest> <pub:attributeFormat>xml</pub:attributeFormat> <pub:attributeTemplate>0</pub:attributeTemplate> <pub:byPassCache>true</pub:byPassCache> <pub:dynamicDataSource> <pub:JDBCDataSource> <pub:JDBCDriverClass></pub:JDBCDriverClass> <pub:JDBCDriverType></pub:JDBCDriverType> <pub:JDBCPassword></pub:JDBCPassword> <pub:JDBCURL></pub:JDBCURL> <pub:JDBCUserName></pub:JDBCUserName> <pub:dataSourceName>Conn1</pub:dataSourceName> </pub:JDBCDataSource> </pub:dynamicDataSource> <pub:reportAbsolutePath>/Test/Employee Report/Employee Report.xdo</pub:reportAbsolutePath> </pub:reportRequest> <pub:userID>Administrator</pub:userID> <pub:password>Administrator</pub:password> </pub:runReport> So I have Conn1 and Conn2 defined that are connections to different databases. I can just flip the name, make the WS call and get the appropriate dataset in my report. Just as an example, here's my web service call java code. Just a case of bringing in the BIP java libs to my java project. publicReportServiceService = new PublicReportServiceService(); PublicReportService publicReportService = publicReportServiceService.getPublicReportService_v11(); String userID = "Administrator"; String password = "Administrator"; ReportRequest rr = new ReportRequest(); rr.setAttributeFormat("xml"); rr.setAttributeTemplate("1"); rr.setByPassCache(true); rr.setReportAbsolutePath("/Test/Employee Report/Employee Report.xdo"); rr.setReportOutputPath("c:\\temp\\output.xml"); BIPDataSource bipds = new BIPDataSource(); JDBCDataSource jds = new JDBCDataSource(); jds.setDataSourceName("Conn1"); bipds.setJDBCDataSource(jds); rr.setDynamicDataSource(bipds); try { publicReportService.runReport(rr, userID, password); } catch (InvalidParametersException e) { e.printStackTrace(); } catch (AccessDeniedException e) { e.printStackTrace(); } catch (OperationFailedException e) { e.printStackTrace(); } } Note, Im no java whiz kid or whizzy old bloke, at least not unless Ive had a coffee. JDeveloper has a nice feature where you point it at the WSDL and it creates everything to support your calling code for you. Couple of things to remember: 1. When you call the service, remember to set the bypass the cache option. Forget it and much scratching of your head and taking my name in vain will ensue. 2. My demo actually hit the same database but used two users, one accessed the base tables another views with the same name. For far too long I thought the connection swapping was not working. I was getting the same results for both users until I realized I was specifying the schema name for the table/view in my query e.g. select * from EMP.EMPLOYEES. So remember to have a generic query that will depend entirely on the connection. Its a neat feature if you want to be able to switch connections and only define a single report and call it remotely. Now if you want the connection to be set dynamically based on the user and the report run via the user interface, thats going to be more tricky ... need to think about that one!

    Read the article

  • Why does this pdo::mysql code crash on windows??

    - by user154107
    Why does this pdo::mysql code crash on windows??? <?php $username = "root"; $password = ""; try { $dsn = "mysql:host=localhost;dbname=employees"; $dbh = new PDO($dsn, $username, $password); $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Connected to database<br />" ; $dbh->exec("DROP TABLE IF EXISTS vCard;"); $dbh->exec("DROP TABLE IF EXISTS emp;"); $table = "CREATE TABLE vCard( id INT(4) NOT NULL PRIMARY KEY, firstName VARCHAR (255), lastName VARCHAR (255), office VARCHAR (255), homePh VARCHAR (13), mobilePh VARCHAR (13))"; $dbh->exec($table); $dbh->beginTransaction(); $dbh->exec("INSERT INTO vCard(id, firstName, lastName, office, homePh, mobilePh) VALUES (4834, 'Randy', 'Lewis', 'SR. Front End Developer', '631-842-3375', '917-435-2245');"); $dbh->exec("INSERT INTO vCard(id, firstName, lastName, office, homePh, mobilePh) VALUES (0766, 'Frank', 'LaGuy', 'Graphic Designer', '631-789-8244', '917-324-9897');"); $dbh->exec("INSERT INTO vCard(id, firstName, lastName, office, homePh, mobilePh) VALUES (6684, 'Donnie', 'Dolemite', 'COO', '631-789-9482', '917-234-1222');"); $dbh->exec("INSERT INTO vCard(id, firstName, lastName, office, homePh, mobilePh) VALUES (8569, '', 'McLovin', 'Actor', '631-842-9786', '917-987-8944');"); $dbh->commit(); echo "Data entered successfully<br/><br/>"; $sql = "SELECT * FROM vCard"; // WHERE firstName = 'Donnie'"; $results = $dbh->query($sql); foreach ($results as $id){ echo "SSN: ". $id['id']." "; echo "First Name: ". $id['firstName']." "; echo "Last Name: ". $id['lastName']."<br/>"; } } catch (PDOException $e) { echo "Failed: " . $e->getMessage(); $dbh->rollback(); } ?> basically this line of code is what triggers Apache to crash.. $sql = "SELECT * FROM vCard"; If I try to select one value like 'id' it'll ... when I try to select more than one value "*" it crashes??????

    Read the article

  • I can't Open my excel file in c#

    - by Ruben Guico
    Hi, Below is my code, i tried to open my excel file in my c# application but the program give's me an error message "Cannot Access "my excel.xls". But when I specify the file path in my string path variable it works, the problem is I need to get the file path from an openFileDialog. using System; using System.IO; using System.Collections.Generic; using System.Text; using System.Data; using System.Windows.Forms; using System.Data.OleDb; using System.Reflection; using MOIE = Microsoft.Office.Interop.Excel; using OFFICE = Microsoft.Office.Core; namespace EmpUploader { public class ExcelCon { private OleDbDataReader reader = null; private OleDbCommand excelCommand = new OleDbCommand(); private OleDbDataAdapter adapter = new OleDbDataAdapter(); private DataTable excelData = new DataTable(); private MOIE.ApplicationClass objExcel = new MOIE.ApplicationClass(); private MOIE.Workbook wb = null; private string myConn = ""; private string strSQL = ""; private string err = ""; private string path2 = ""; private int sheetCount = 0; private OleDbConnection Con = new OleDbConnection(""); #region "excel interop prarameters" private static object xl_missing = Type.Missing; private static object xl_true = true; private static object xl_false = false; private object xl_update_links = xl_missing; private object xl_read_only = xl_missing; private object xl_format = xl_missing; private object xl_password = xl_missing; private object xl_write_res_password = xl_missing; private object xl_ignore_read_only = xl_missing; private object xl_origin = xl_missing; private object xl_delimiter = xl_missing; private object xl_editable = xl_missing; private object xl_notify = xl_missing; private object xl_converter = xl_missing; private object xl_add_to_mru = xl_missing; private object xl_local = xl_missing; private object xl_corrupt_load = xl_missing; #endregion } //MY CODE FOR OPENING THE EXCEL //note that my file path came from an openfiledialog public void InitializeConnection(string path) { //connection string for excel myConn = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + path + "; Extended Properties =Excel 8.0"; Con.ConnectionString = myConn; Con.Open(); //this is the sample specified path that worked when i test my application //path = @"C:\shinetsu p5 emp list.xls"; objExcel.Visible = false; wb = objExcel.Workbooks.Open(path, xl_update_links, xl_read_only, xl_format, xl_password, xl_write_res_password, xl_ignore_read_only, xl_origin, xl_delimiter, xl_editable, xl_notify, xl_converter, xl_add_to_mru, xl_local, xl_corrupt_load); sheetCount = wb.Worksheets.Count; } }

    Read the article

  • Retrieving the Selected value dynamically in JQuery

    - by Chakradhar
    i have this html, this is generated dynamically based on question number <fieldset id="selectfield"> <label class="select">What ur is Profession? </label> <br> <div class="ui-select"><a href="#" role="button" id="72+_select-button" aria-haspopup="true" aria-owns="72+_select-menu" data-theme="c" class="ui-btn ui-btn-icon-right ui-btn-corner-all ui-shadow ui-btn-hover-c ui-btn-up-c"><span class="ui-btn-inner ui-btn-corner-all" aria-hidden="true"><span class="ui-btn-text">Business</span><span class="ui-icon ui-icon-arrow-d ui-icon-shadow"></span></span></a> <select name="selectedObjects" id="72+_select" data-native-menu="false" tabindex="-1"> <option value="-1">--Select--</option> <option value="769">Salaried</option> <option selected="selected" value="770">Business</option> <option value="771">Self Emp</option> </select></div> </fieldset> click button is <div data-theme="c" class="ui-btn ui-btn-corner-all ui-shadow ui-btn-hover-c ui-btn-up-c" aria-disabled="false"><span class="ui-btn-inner ui-btn-corner-all" aria-hidden="true"><span class="ui-btn-text">Next</span></span> <input type="submit" id="72+_b" onclick="return SaveDropDown(this);" value="Next" class="ui-btn-hidden" aria-disabled="false"> </div> i have written this JS in SaveDropDown(this) function SaveDropDown(button) { var fieldsetName = getQuestionName(button.id)+'+_select'; var select = $(fieldsetName +"option:selected").val(); return false; } the questionname function is function getQuestionName(buttonid) { var splitstr = buttonid.split('+'); var fieldsetName = '#' + splitstr[0]; return fieldsetName; } but its returning the undefined how do i retrieve the select value dynamically. any help is appreciated.

    Read the article

  • form inside tabview doesn't work

    - by user3536737
    i am working with jsf and primefaces , and here is what 've tried well i want to creat a tabview that get data from an arraylist in my bean i get for exemple 4 tabs , and inside each one i've created a hidden panel where i have a form with 2 input text to update informations , do i display the panel when i click on the second button Update , after that my panel is not hidden anymore , and i set the new values and click on the second button to update the informations , the problem is that the updating and the execution is working only for the first tab , it means when i try to update the new informations it works for the first one and for the other tabs it doesn't here is the code <p:tab title="#{rr.nom_ressource}"> <h:panelGrid> <h:graphicImage value="Ressources/images/emp.jpg" style="vertical-align:middle" /> <span style="font-size:15px; width:170px; display:inline-block;"> Nom : #{rr.nom_ressource} Type: #{rr.type_ressource} Specification: #{rr.experience} </span> <h:commandButton image="Ressources/images/delete.jpg" actionListener="#{SelectBean.act}" update=":form" style="vertical-align:middle" > Update </h:commandButton> <h:commandButton update=":outPanel" actionListener="#{SelectBean.mod1()}" image="Ressources/images/update.png" style="vertical-align:middle" > Modifier </h:commandButton> <h:form id="form111"> <p:growl id="growl" showDetail="true" sticky="true" /> <p:panel rendered ="#{SelectBean.bol}" closable="true" toggleable="true" id="outPanel" styleClass="outPanel" widgetVar="outpanel"> <h:outputLabel value="Nom " /> <h:inputText value="#{SelectBean.nom}" /> <br/> <h:outputLabel value="Experience " /> <h:inputText value="#{SelectBean.exp}" /> <br/> <h:commandButton value="Update" action="#{SelectBean.done}"/> </p:panel> </h:form> </h:panelGrid> </p:tab> for my managedbean the code is correct i think the problem is here

    Read the article

  • ODI 12c - Parallel Table Load

    - by David Allan
    In this post we will look at the ODI 12c capability of parallel table load from the aspect of the mapping developer and the knowledge module developer - two quite different viewpoints. This is about parallel table loading which isn't to be confused with loading multiple targets per se. It supports the ability for ODI mappings to be executed concurrently especially if there is an overlap of the datastores that they access, so any temporary resources created may be uniquely constructed by ODI. Temporary objects can be anything basically - common examples are staging tables, indexes, views, directories - anything in the ETL to help the data integration flow do its job. In ODI 11g users found a few workarounds (such as changing the technology prefixes - see here) to build unique temporary names but it was more of a challenge in error cases. ODI 12c mappings by default operate exactly as they did in ODI 11g with respect to these temporary names (this is also true for upgraded interfaces and scenarios) but can be configured to support the uniqueness capabilities. We will look at this feature from two aspects; that of a mapping developer and that of a developer (of procedures or KMs). 1. Firstly as a Mapping Developer..... 1.1 Control when uniqueness is enabled A new property is available to set unique name generation on/off. When unique names have been enabled for a mapping, all temporary names used by the collection and integration objects will be generated using unique names. This property is presented as a check-box in the Property Inspector for a deployment specification. 1.2 Handle cleanup after successful execution Provided that all temporary objects that are created have a corresponding drop statement then all of the temporary objects should be removed during a successful execution. This should be the case with the KMs developed by Oracle. 1.3 Handle cleanup after unsuccessful execution If an execution failed in ODI 11g then temporary tables would have been left around and cleaned up in the subsequent run. In ODI 12c, KM tasks can now have a cleanup-type task which is executed even after a failure in the main tasks. These cleanup tasks will be executed even on failure if the property 'Remove Temporary Objects on Error' is set. If the agent was to crash and not be able to execute this task, then there is an ODI tool (OdiRemoveTemporaryObjects here) you can invoke to cleanup the tables - it supports date ranges and the like. That's all there is to it from the aspect of the mapping developer it's much, much simpler and straightforward. You can now execute the same mapping concurrently or execute many mappings using the same resource concurrently without worrying about conflict.  2. Secondly as a Procedure or KM Developer..... In the ODI Operator the executed code shows the actual name that is generated - you can also see the runtime code prior to execution (introduced in 11.1.1.7), for example below in the code type I selected 'Pre-executed Code' this lets you see the code about to be processed and you can also see the executed code (which is the default view). References to the collection (C$) and integration (I$) names will be automatically made unique by using the odiRef APIs - these objects will have unique names whenever concurrency has been enabled for a particular mapping deployment specification. It's also possible to use name uniqueness functions in procedures and your own KMs. 2.1 New uniqueness tags  You can also make your own temporary objects have unique names by explicitly including either %UNIQUE_STEP_TAG or %UNIQUE_SESSION_TAG in the name passed to calls to the odiRef APIs. Such names would always include the unique tag regardless of the concurrency setting. To illustrate, let's look at the getObjectName() method. At <% expansion time, this API will append %UNIQUE_STEP_TAG to the object name for collection and integration tables. The name parameter passed to this API may contain  %UNIQUE_STEP_TAG or %UNIQUE_SESSION_TAG. This API always generates to the <? version of getObjectName() At execution time this API will replace the unique tag macros with a string that is unique to the current execution scope. The returned name will conform to the name-length restriction for the target technology, and its pattern for the unique tag. Any necessary truncation will be performed against the initial name for the object and any other fixed text that may have been specified. Examples are:- <?=odiRef.getObjectName("L", "%COL_PRFEMP%UNIQUE_STEP_TAG", "D")?> SCOTT.C$_EABH7QI1BR1EQI3M76PG9SIMBQQ <?=odiRef.getObjectName("L", "EMP%UNIQUE_STEP_TAG_AE", "D")?> SCOTT.EMPAO96Q2JEKO0FTHQP77TMSAIOSR_ Methods which have this kind of support include getFrom, getTableName, getTable, getObjectShortName and getTemporaryIndex. There are APIs for retrieving this tag info also, the getInfo API has been extended with the following properties (the UNIQUE* properties can also be used in ODI procedures); UNIQUE_STEP_TAG - Returns the unique value for the current step scope, e.g. 5rvmd8hOIy7OU2o1FhsF61 Note that this will be a different value for each loop-iteration when the step is in a loop. UNIQUE_SESSION_TAG - Returns the unique value for the current session scope, e.g. 6N38vXLrgjwUwT5MseHHY9 IS_CONCURRENT - Returns info about the current mapping, will return 0 or 1 (only in % phase) GUID_SRC_SET - Returns the UUID for the current source set/execution unit (only in % phase) The getPop API has been extended with the IS_CONCURRENT property which returns info about an mapping, will return 0 or 1.  2.2 Additional APIs Some new APIs are provided including getFormattedName which will allow KM developers to construct a name from fixed-text or ODI symbols that can be optionally truncate to a max length and use a specific encoding for the unique tag. It has syntax getFormattedName(String pName[, String pTechnologyCode]) This API is available at both the % and the ? phase.  The format string can contain the ODI prefixes that are available for getObjectName(), e.g. %INT_PRF, %COL_PRF, %ERR_PRF, %IDX_PRF alongwith %UNIQUE_STEP_TAG or %UNIQUE_SESSION_TAG. The latter tags will be expanded into a unique string according to the specified technology. Calls to this API within the same execution context are guaranteed to return the same unique name provided that the same parameters are passed to the call. e.g. <%=odiRef.getFormattedName("%COL_PRFMY_TABLE%UNIQUE_STEP_TAG_AE", "ORACLE")%> <?=odiRef.getFormattedName("%COL_PRFMY_TABLE%UNIQUE_STEP_TAG_AE", "ORACLE")?> C$_MY_TAB7wDiBe80vBog1auacS1xB_AE <?=odiRef.getFormattedName("%COL_PRFMY_TABLE%UNIQUE_STEP_TAG.log", "FILE")?> C2_MY_TAB7wDiBe80vBog1auacS1xB.log 2.3 Name length generation  As part of name generation, the length of the generated name will be compared with the maximum length for the target technology and truncation may need to be applied. When a unique tag is included in the generated string it is important that uniqueness is not compromised by truncation of the unique tag. When a unique tag is NOT part of the generated name, the name will be truncated by removing characters from the end - this is the existing 11g algorithm. When a unique tag is included, the algorithm will first truncate the <postfix> and if necessary  the <prefix>. It is recommended that users will ensure there is sufficient uniqueness in the <prefix> section to ensure uniqueness of the final resultant name. SUMMARY To summarize, ODI 12c make it much simpler to utilize mappings in concurrent cases and provides APIs for helping developing any procedures or custom knowledge modules in such a way they can be used in highly concurrent, parallel scenarios. 

    Read the article

  • C# Extension Methods - To Extend or Not To Extend...

    - by James Michael Hare
    I've been thinking a lot about extension methods lately, and I must admit I both love them and hate them. They are a lot like sugar, they taste so nice and sweet, but they'll rot your teeth if you eat them too much.   I can't deny that they aren't useful and very handy. One of the major components of the Shared Component library where I work is a set of useful extension methods. But, I also can't deny that they tend to be overused and abused to willy-nilly extend every living type.   So what constitutes a good extension method? Obviously, you can write an extension method for nearly anything whether it is a good idea or not. Many times, in fact, an idea seems like a good extension method but in retrospect really doesn't fit.   So what's the litmus test? To me, an extension method should be like in the movies when a person runs into their twin, separated at birth. You just know you're related. Obviously, that's hard to quantify, so let's try to put a few rules-of-thumb around them.   A good extension method should:     Apply to any possible instance of the type it extends.     Simplify logic and improve readability/maintainability.     Apply to the most specific type or interface applicable.     Be isolated in a namespace so that it does not pollute IntelliSense.     So let's look at a few examples in relation to these rules.   The first rule, to me, is the most important of all. Once again, it bears repeating, a good extension method should apply to all possible instances of the type it extends. It should feel like the long lost relative that should have been included in the original class but somehow was missing from the family tree.    Take this nifty little int extension, I saw this once in a blog and at first I really thought it was pretty cool, but then I started noticing a code smell I couldn't quite put my finger on. So let's look:       public static class IntExtensinos     {         public static int Seconds(int num)         {             return num * 1000;         }           public static int Minutes(int num)         {             return num * 60000;         }     }     This is so you could do things like:       ...     Thread.Sleep(5.Seconds());     ...     proxy.Timeout = 1.Minutes();     ...     Awww, you say, that's cute! Well, that's the problem, it's kitschy and it doesn't always apply (and incidentally you could achieve the same thing with TimeStamp.FromSeconds(5)). It's syntactical candy that looks cool, but tends to rot and pollute the code. It would allow things like:       total += numberOfTodaysOrders.Seconds();     which makes no sense and should never be allowed. The problem is you're applying an extension method to a logical domain, not a type domain. That is, the extension method Seconds() doesn't really apply to ALL ints, it applies to ints that are representative of time that you want to convert to milliseconds.    Do you see what I mean? The two problems, in a nutshell, are that a) Seconds() called off a non-time value makes no sense and b) calling Seconds() off something to pass to something that does not take milliseconds will be off by a factor of 1000 or worse.   Thus, in my mind, you should only ever have an extension method that applies to the whole domain of that type.   For example, this is one of my personal favorites:       public static bool IsBetween<T>(this T value, T low, T high)         where T : IComparable<T>     {         return value.CompareTo(low) >= 0 && value.CompareTo(high) <= 0;     }   This allows you to check if any IComparable<T> is within an upper and lower bound. Think of how many times you type something like:       if (response.Employee.Address.YearsAt >= 2         && response.Employee.Address.YearsAt <= 10)     {     ...     }     Now, you can instead type:       if(response.Employee.Address.YearsAt.IsBetween(2, 10))     {     ...     }     Note that this applies to all IComparable<T> -- that's ints, chars, strings, DateTime, etc -- and does not depend on any logical domain. In addition, it satisfies the second point and actually makes the code more readable and maintainable.   Let's look at the third point. In it we said that an extension method should fit the most specific interface or type possible. Now, I'm not saying if you have something that applies to enumerables, you create an extension for List, Array, Dictionary, etc (though you may have reasons for doing so), but that you should beware of making things TOO general.   For example, let's say we had an extension method like this:       public static T ConvertTo<T>(this object value)     {         return (T)Convert.ChangeType(value, typeof(T));     }         This lets you do more fluent conversions like:       double d = "5.0".ConvertTo<double>();     However, if you dig into Reflector (LOVE that tool) you will see that if the type you are calling on does not implement IConvertible, what you convert to MUST be the exact type or it will throw an InvalidCastException. Now this may or may not be what you want in this situation, and I leave that up to you. Things like this would fail:       object value = new Employee();     ...     // class cast exception because typeof(IEmployee) != typeof(Employee)     IEmployee emp = value.ConvertTo<IEmployee>();       Yes, that's a downfall of working with Convertible in general, but if you wanted your fluent interface to be more type-safe so that ConvertTo were only callable on IConvertibles (and let casting be a manual task), you could easily make it:         public static T ConvertTo<T>(this IConvertible value)     {         return (T)Convert.ChangeType(value, typeof(T));     }         This is what I mean by choosing the best type to extend. Consider that if we used the previous (object) version, every time we typed a dot ('.') on an instance we'd pull up ConvertTo() whether it was applicable or not. By filtering our extension method down to only valid types (those that implement IConvertible) we greatly reduce our IntelliSense pollution and apply a good level of compile-time correctness.   Now my fourth rule is just my general rule-of-thumb. Obviously, you can make extension methods as in-your-face as you want. I included all mine in my work libraries in its own sub-namespace, something akin to:       namespace Shared.Core.Extensions { ... }     This is in a library called Shared.Core, so just referencing the Core library doesn't pollute your IntelliSense, you have to actually do a using on Shared.Core.Extensions to bring the methods in. This is very similar to the way Microsoft puts its extension methods in System.Linq. This way, if you want 'em, you use the appropriate namespace. If you don't want 'em, they won't pollute your namespace.   To really make this work, however, that namespace should only include extension methods and subordinate types those extensions themselves may use. If you plant other useful classes in those namespaces, once a user includes it, they get all the extensions too.   Also, just as a personal preference, extension methods that aren't simply syntactical shortcuts, I like to put in a static utility class and then have extension methods for syntactical candy. For instance, I think it imaginable that any object could be converted to XML:       namespace Shared.Core     {         // A collection of XML Utility classes         public static class XmlUtility         {             ...             // Serialize an object into an xml string             public static string ToXml(object input)             {                 var xs = new XmlSerializer(input.GetType());                   // use new UTF8Encoding here, not Encoding.UTF8. The later includes                 // the BOM which screws up subsequent reads, the former does not.                 using (var memoryStream = new MemoryStream())                 using (var xmlTextWriter = new XmlTextWriter(memoryStream, new UTF8Encoding()))                 {                     xs.Serialize(xmlTextWriter, input);                     return Encoding.UTF8.GetString(memoryStream.ToArray());                 }             }             ...         }     }   I also wanted to be able to call this from an object like:       value.ToXml();     But here's the problem, if i made this an extension method from the start with that one little keyword "this", it would pop into IntelliSense for all objects which could be very polluting. Instead, I put the logic into a utility class so that users have the choice of whether or not they want to use it as just a class and not pollute IntelliSense, then in my extensions namespace, I add the syntactical candy:       namespace Shared.Core.Extensions     {         public static class XmlExtensions         {             public static string ToXml(this object value)             {                 return XmlUtility.ToXml(value);             }         }     }   So now it's the best of both worlds. On one hand, they can use the utility class if they don't want to pollute IntelliSense, and on the other hand they can include the Extensions namespace and use as an extension if they want. The neat thing is it also adheres to the Single Responsibility Principle. The XmlUtility is responsible for converting objects to XML, and the XmlExtensions is responsible for extending object's interface for ToXml().

    Read the article

  • PHP - Accessing a value selected in Combobox

    - by Pavitar
    I want to write a code that should let me select from a drop down list and onClick of a button load the data from a mysql database.However I cannot access the value selected in the drop down menu.I have tried to access them by $_POST['var_name'] but still can't do it. I'm new to PHP. Following is my code: <?php function load(){ $department = $_POST['dept']; $employee = $_POST['emp']; //echo "$department"; //echo "$employee"; $con = mysqli_connect("localhost", "root", "pwd", "payroll"); $rs = $con->query("select * from dept where deptno='$department'"); $row = $rs->fetch_row(); $n = $row[0]; $rs->free(); $con->close(); } ?> <html> <head> <title>Payroll</title> </head> <body> <h1 align="center">IIT Department</h1> <form method="post"> <table align="center"> <tr> <td> Dept Number: <select name="dept"> <option value="10" selected="selected">10</option> <option value="20">20</option> <option value="30">30</option> <option value="40">40</option> </select> </td> <td> <input type="button" value="ShowDeptEmp" name="btn1"> </td> <td> Job: <select name="job"> <option value="President" selected="selected">President</option> <option value="Manager">Manager</option> <option value="Clerk">Clerk</option> <option value="Salesman">Salesman</option> <option value="Analyst">Analyst</option> </select> </td> <td> <input type="button" value="ShowJobEmp" name="btn1"> </td> </tr> </table> </form> <?php if(isset($_POST['dept']) && $_POST['dept'] != "") load(); ?> </body> </html>

    Read the article

< Previous Page | 3 4 5 6 7 8  | Next Page >