Search Results

Search found 1372 results on 55 pages for 'userid'.

Page 14/55 | < Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >

  • How to read a complex view model on POST?

    - by Interfector
    Hello, I have an user view model that has the following properties: public User user; public List<Language> Languages; I send the above model to the view and use html helpers to build the form, so I end up with something like: <form action="/Users/Edit/5" method="post"><input id="user_UserId" name="user.UserId" type="hidden" value="5" /> First Name Last Name Email Language - en en Now, I try to read the POST in something that initially was something like : [AcceptVerbs( HttpVerbs.Post )] public ActionResult Edit( int UserId, FormCollection form ) { and cannot get the user.UserId variable, user.FirstName variable etc. Any idea what needs to be done to be able to read this kind of POST request. I'm kind of reluctant to modifying my ViewModel as it is very simple and easy to maintain as it is. Thank you.

    Read the article

  • PHP and MySQL SELECT problem.

    - by R.I.P.coalMINERS
    Trying to check if a name is already stored in the database from the login user. The name is a set of dynamic arrays entered by the user threw a set of dynamic form fields added by the user. Can some show me how to check and see if the name is already entered by the login user? I know my code can't be right. Thanks! MySQL code. SELECT * FROM names WHERE name = '" . $_POST['name'] . "' AND userID = '$userID' Here is the MySQL table. CREATE TABLE names ( id INT UNSIGNED NOT NULL AUTO_INCREMENT, userID INT NOT NULL, name VARCHAR(255) NOT NULL, meaning VARCHAR(255) NOT NULL, PRIMARY KEY (id) );

    Read the article

  • get js file query param from inside it

    - by vsync
    I load this file with some query param like this: src='somefile.js?userId=123' I wrote the below function in 'somefile.js' file that reads the 'userId' query param but I feel this is not the best approach. Frankly, its quite ugly. Is there a better way? function getId(){ var scripts = document.getElementsByTagName('script'), script; for(var i in scripts){ if( scripts.hasOwnProperty(i) && scripts[i].src.indexOf('somefile.js') != -1 ) var script = scripts[i]; } var s = (script.getAttribute.length !== undefined) ? script.getAttribute('src') : script.getAttribute('src', 2); return getQueryParams('userId',s); };

    Read the article

  • What would be the best approach for this?

    - by chobo
    I have a site which has an area that requires authentication. Right now I use the roles attribute on all the controllers in that area, and I run a query to retrieve that users ID, and all their settings. It seems like a code or design smell to me that I am retrieving the userid and settings each time a controller in that area loads up? I'm not sure if I should be using sessions, or if ASP.Net MVC 2.0 provides some unique way to handle this. Another concern is security. Overall, I don't really know which way to turn. Design wise I would like the userId and settings retrieved only once when the user logs into the area. Right now I grab the userId each time a controller loads up, and then if required, I query the database for their settings each time as well.

    Read the article

  • Hashing and salting values

    - by Avanst
    I am developing a small web app that internally authenticates users. Once the user is authenticated my web app then passes some information such as userID and Person's name to a third party web application. The third party developer is suggesting that we hash and salt the values. Forgive my ignorance, but what exactly does that mean? I am writing the app in Java. So what I am planning on doing is hashing the userID, Person's name, and some Math.random() value as the salt with Apache Commons Digest Utils SHA512 and passing that hashed string along with the userID and person's name. Is that the standard practice? I should be passing the third party the salt as well correct?

    Read the article

  • One-to-many relationship related to many tables

    - by Andrey
    I have a scenario where: there are two (or more) tables that represent independent items. lets say Users and Companies Both of these tables need addresses stored. Each one can have one or more address In a normal 1 to many scenario Addresses table woudl just have a UserId or a CompanyId creating a normal 1 to many relationship. In this case i have a few approaches i can think of the Addresses table could have both a UserId and a CompanyId and only one would be used for each record. 2 keys could be used ObjectId and ObjectType So Object id would have a UserId or a CompanyId, and ObjectType woudl be User or Company Create an ObjectTable and add ObjectId to Users and Companies. Addresses would then have an OjbectId I do not really like any of these solutions. i am wondering what is the best approach here. On another note i will most likely user linqtosql for my data access layer.

    Read the article

  • [grails + xfire] How to handle errors in SOAP services?

    - by Mulone
    Hi all, I'm implementing a web service on the xfire plugin. I was wondering how I'm supposed to handle the errors. I tried with this setup but the error is not returned to the SOAP client: GaSession[] myMethod( String userId ) throws MyException{ GaUser user = GaUser.findByUserId( userId ) if (!user) throw new MyException("user ${userId} does not exist") // do stuff and return valid results } Is there a standard way to handle errors and return them to the client in a clear way? My log is full of messages like: 2010-06-13 18:20:40,926 [Thread-289] DEBUG aegis.XMLClassMetaInfoManager - Mapping file : /com/mycompany/MyClass.aegis.xml not found. Is there a way to fix this? Cheers!

    Read the article

  • My cookies won't stay (PHP).

    - by RemiX
    I'm building an autologin system using cookies, but one fundamental part of the functionality of the cookies fails: they are non-persistent over different sessions - or even pages! In my login script, I set the cookies like this: setcookie('userID', $userID, time()+86400); // (edited after replies) $userID has a value. Then I print the $_COOKIE variable and it says array(['base_usid'] = 1); So that's good, but when I click the home page and print the $_COOKIE variable there, it says NULL. Does anyone see the problem?

    Read the article

  • mysql select multiple rows in join

    - by julio
    Hi-- I have a simple mySQL problem-- I have two tables, one is a user's table, and one is a photos table (each user can upload multiple photos). I'd like to write a query to join these tables, so I can pull all photos associated with a user (up to a certain limit). However, when I do something obvious like this: SELECT *.a, *.b FROM user_table a JOIN photos_table b ON a.id = b.userid it returns a.id, a.name, a.email, a.address, b.id, b.userid, b.photo_title, b.location but it only returns a single photo. Is there a way to return something like: a.id, a.name, a.email, a.address, b.id, b.userid, b.photo_title, b.location, b.id2, b.photo_title2, b.location2 etc. . . for a given LIMIT of photos? Thanks for any ideas.

    Read the article

  • ASP.NET check if LinqToEntities returned something or not.

    - by Alex
    How to make this method return boolean value, depending on query return. False - nothing, True - data exists. Before i just returned int from uniqueQuote.Count() but does not look like great method. Thank you! private bool CheckEnquiryUser(int enquiryId, Guid userId) { int selectedEnquiryId = enquiryId; Guid currentUserId = userId; Entities ctx3 = new Entities(); var uniqueQuote = from quot in ctx3.Enquiries.Include("aspnet_Users") where quot.EnquiryId == selectedEnquiryId && quot.aspnet_Users.UserId == currentUserId select quot; bool exist = uniqueQuote; return exist;

    Read the article

  • How do stop form posting to mysql if database contains a specific ID?

    - by user342391
    I have a form that I am using to post data to mysql. Before submitting the form I want to check the database and see if there are any fields in the column 'customerid' that equal 'userid' and if so not to post the form. Basically, I am trying to limit my users from posting more than once. Users will be able to login to my system and make ONE post. They will be able to delete and modify their post but are only limited to one post. How would I do this??? Code so far: <?php include '../login/dbc.php'; page_protect(); $userid = $_SESSION['user_id']; $sql="INSERT INTO content (customerid, weburl, title, description) VALUES ('$_POST[userid]','$_POST[webaddress]','$_POST[pagetitle]','$_POST[pagedescription]')"; if (!mysql_query($sql)) { die('Error: ' . mysql_error()); } echo "1 record added"; ?>

    Read the article

  • Passing Values from a View to itself with parameters getting null values ?

    - by vsj
    Hi all, I am trying to get values from a view which i have the code below and I am taking the start date value from the view input text box and posting it back but I am still getting null except for the apikey and userkey.Here are the two views.. public ActionResult View1(string apiKey, string userId) { StartGoalViewModel vm = new StartGoalViewModel(); vm.ApiKey = apiKey; vm.UserId = userId; vm.GoalTypeId =1; vm.StartDate = null; return View(vm); } VIEW1.ASPX <% Html.BeginForm(); %> <%= Html.TextBox("name", Model.StartDate) %> <input type="submit" value="Start" /> <% Html.EndForm(); %> [HttpPost] public ActionResult VIEW1 (StartGoalViewModel fm) { // I get StartDate null... }

    Read the article

  • How to add attributes to a HTML element in a valid way?

    - by Click Upvote
    I want to be able to add an attribute to a HTML element to be able to identify what its referring to. E.g if I have a list of names and a checkbox next to each name, like this: <div id="users"> Bob smith <input type=checkbox /> </div> And when a checkbox is clicked and the event handler function for it is called, I want to be able to identify which user was selected/unselected. Ideally I'm looking for something like this: <input type=checkbox data-userId = "xxx" /> Then when its clicked: function handleClick() { var userId = $(this).attr('data-userId'); } However I'm looking to do this in a way that won't break my HTML validation, and would still be valid HTML and work in all browsers. Any suggestions?

    Read the article

  • Index outof range? Automatica generate field .How to manipulate GridView2.Columns as BoundField;

    - by mike
    Index outof range?GridView2.Columns[6] as BoundField I use Automatica generate field . How to manipulate GridView2.Columns as BoundField with auto-generate feather? JobPostDataContext db = new JobPostDataContext(); var query = from j in db.JobLists join u in db.UserLists on j.UserID equals u.UserID where j.JobTitle.Contains(this.TextBox1.Text) select new { j.JobID, j.JobTitle, j.Summary, j.Details, j.CompanyName, j.CompanyEmail, j.DatePosted, j.UserID, u.City, u.State, u.Country }; GridView2.DataSource = query; GridView2.DataBind(); BoundField DatePosted = GridView2.Columns[6] as BoundField; DatePosted.DataFormatString = "{0:MMM,dd yy}";

    Read the article

  • PHP - if == not working for 0 or ""

    - by user2933212
    I am checking the validation of the request with an if query, if ($request_userid == $userid) { ... } Thats working as expected. But further testing has shown, that if $request_userid or $userid is 0 or "", then the condition is true and the script runs the if query but it shouldn't. I am currently solving it with: if ($userid == "" ) { exit ("exit"); } But I don't think that this is the right way? Can you explain why it doesn’t work with the if query and what would be the correct way to check it?

    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

  • SOCharts: Charts by Tags

    - by abhin4v
    Screenshot I created this small app as a weekend hack. It shows the reputations, upvotes, downvotes and accepted answers for a user against the tags for the answers. About I wanted to know how may upvotes I was away from getting the bronze badge for the clojure tag. But I could not find any straightforward way of doing that. So I wrote this app (in Clojure, of course). The SO API is used for the data and the charts are created using the Google Chart API. The charts are opened in the default browser. License Licensed under EPL 1.0. Download If you have Clojure and Leiningen installed, you can simply get the code from https://gist.github.com/725331, save it as socharts.clj and then run lein repl -e "(load \"socharts\")(refer 'socharts.socharts)(-main)" for launching the Swing UI If you don't have Clojure installed, but have Java then download the standalone jar from http://dl.dropbox.com/u/5247/socharts-1.0.0-standalone.jar and run it as javaw -jar socharts-1.0.0-standalone.jar Once the UI is launched, just type your user id in the input box and press <ENTER>. It will take some time to download the data from the SO API (the progress bar shows the download progress) and then it will open the charts in your default browser. You can also run it as a command line app by running lein repl -e "(load \"socharts\")(refer 'socharts.socharts)(-main <userid>)" or java -jar socharts-1.0.0-standalone.jar <userid> where you replace <userid> with your user id. Be warned that because of a missing feature in the SO API, it will fetch the data for each question you have answered. So the maximum limit is 10000 answers (the SO API call limit). Platform All platforms with Java 1.6. Contact You can reach me at abhinav [at] abhinavsarkar [dot] net. Please report bugs/comments/suggestions as answers to this post. Code Code was written in Clojure with the UI in Swing. It is available at https://gist.github.com/725331. It's a public gist so your can fork it if you like to do some changes.

    Read the article

  • Best way to throw exception and avoid code duplication

    - by JF Dion
    I am currently writing code and want to make sure all the params that get passed to a function/method are valid. Since I am writing in PHP I don't have access to all the facilities of other languages like C, C++ or Java to check for parameters values and types public function inscriptionExists($sectionId, $userId) // PHP vs. public boolean inscriptionExists(int sectionId, int userId) // Java So I have to rely on exceptions if I want to make sure that my params are both integers. Since I have a lot of places where I need to check for param validity, what would be the best way to create a validation/exception machine and avoid code duplication? I was thinking on a static factory (since I don't want to pass it to all of my classes) with a signature like: public static function factory ($value, $valueType, $exceptionType = 'InvalidArgumentException'); Which would then call the right sub process to validate based on the type. Am I on the right way, or am I going completely off the road and overthinking my problem?

    Read the article

  • get mysql_real_escape is giving me errors when I try and add security to my website

    - by Mike
    I tried doing this: @ $db = new myConnectDB(); $beerName = mysql_real_escape_string($beerName); $beerID = mysql_real_escape_string($beerID); $brewery = mysql_real_escape_string($brewery); $style = mysql_real_escape_string($style); $userID = mysql_real_escape_string($userID); $abv = mysql_real_escape_string($abv); $ibu = mysql_real_escape_string($ibu); $breweryID = mysql_real_escape_string($breweryID); $icon = mysql_real_escape_string($icon); I get this error: Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user

    Read the article

  • SQL ADO.NET shortcut extensions (old school!)

    - by Jeff
    As much as I love me some ORM's (I've used LINQ to SQL quite a bit, and for the MSDN/TechNet Profile and Forums we're using NHibernate more and more), there are times when it's appropriate, and in some ways more simple, to just throw up so old school ADO.NET connections, commands, readers and such. It still feels like a pain though to new up all the stuff, make sure it's closed, blah blah blah. It's pretty much the least favorite task of writing data access code. To minimize the pain, I have a set of extension methods that I like to use that drastically reduce the code you have to write. Here they are... public static void Using(this SqlConnection connection, Action<SqlConnection> action) {     connection.Open();     action(connection);     connection.Close(); } public static SqlCommand Command(this SqlConnection connection, string sql){    var command = new SqlCommand(sql, connection);    return command;}public static SqlCommand AddParameter(this SqlCommand command, string parameterName, object value){    command.Parameters.AddWithValue(parameterName, value);    return command;}public static object ExecuteAndReturnIdentity(this SqlCommand command){    if (command.Connection == null)        throw new Exception("SqlCommand has no connection.");    command.ExecuteNonQuery();    command.Parameters.Clear();    command.CommandText = "SELECT @@IDENTITY";    var result = command.ExecuteScalar();    return result;}public static SqlDataReader ReadOne(this SqlDataReader reader, Action<SqlDataReader> action){    if (reader.Read())        action(reader);    reader.Close();    return reader;}public static SqlDataReader ReadAll(this SqlDataReader reader, Action<SqlDataReader> action){    while (reader.Read())        action(reader);    reader.Close();    return reader;} It has been awhile since I've really revisited these, so you will likely find opportunity for further optimization. The bottom line here is that you can chain together a bunch of these methods to make a much more concise database call, in terms of the code on your screen, anyway. Here are some examples: public Dictionary<string, string> Get(){    var dictionary = new Dictionary<string, string>();    _sqlHelper.GetConnection().Using(connection =>        connection.Command("SELECT Setting, [Value] FROM Settings")            .ExecuteReader()            .ReadAll(r => dictionary.Add(r.GetString(0), r.GetString(1))));    return dictionary;} or... public void ChangeName(User user, string newName){    _sqlHelper.GetConnection().Using(connection =>         connection.Command("UPDATE Users SET Name = @Name WHERE UserID = @UserID")            .AddParameter("@Name", newName)            .AddParameter("@UserID", user.UserID)            .ExecuteNonQuery());} The _sqlHelper.GetConnection() is just some other code that gets a connection object for you. You might have an even cleaner way to take that step out entirely. This looks more fluent, and the real magic sauce for me is the reader bits where you can put any kind of arbitrary method in there to iterate over the results.

    Read the article

  • OAuth with RestSharp in Windows Phone

    - by midoBB
    Nearly every major API provider uses OAuth for the user authentication and while it is easy to understand the concept, using it in a Windows Phone app isn’t pretty straightforward. So for this quick tutorial we will be using RestSharp for WP7 and the API from getglue.com (an entertainment site) to authorize the user. So the first step is to get the OAuth request token and then we redirect our browserControl to the authorization URL private void StartLogin() {   var client = new RestClient("https://api.getglue.com/"); client.Authenticator = OAuth1Authenticator.ForRequestToken("ConsumerKey", "ConsumerSecret"); var request = new RestRequest("oauth/request_token"); client.ExecuteAsync(request, response => { _oAuthToken = GetQueryParameter(response.Content, "oauth_token"); _oAuthTokenSecret = GetQueryParameter(response.Content, "oauth_token_secret"); string authorizeUrl = "http://getglue.com/oauth/authorize" + "?oauth_token=" + _oAuthToken + "&style=mobile"; Dispatcher.BeginInvoke(() => { browserControl.Navigate(new Uri(authorizeUrl)); }); }); } private static string GetQueryParameter(string input, string parameterName) { foreach (string item in input.Split('&')) { var parts = item.Split('='); if (parts[0] == parameterName) { return parts[1]; } } return String.Empty; } Then we listen to the browser’s Navigating Event private void Navigating(Microsoft.Phone.Controls.NavigatingEventArgs e) { if (e.Uri.AbsoluteUri.Contains("oauth_callback")) { var arguments = e.Uri.AbsoluteUri.Split('?'); if (arguments.Length < 1) return; GetAccessToken(arguments[1]); } } private void GetAccessToken(string uri) { var requestToken = GetQueryParameter(uri, "oauth_token"); var client = new RestClient("https://api.getglue.com/"); client.Authenticator = OAuth1Authenticator.ForAccessToken(ConsumerKey, ConsumerSecret, _oAuthToken, _oAuthTokenSecret); var request = new RestRequest("oauth/access_token"); client.ExecuteAsync(request, response => { AccessToken = GetQueryParameter(response.Content, "oauth_token"); AccessTokenSecret = GetQueryParameter(response.Content, "oauth_token_secret"); UserId = GetQueryParameter(response.Content, "glue_userId"); }); } Now to test it we can access the user’s friends list var client = new RestClient("http://api.getglue.com/v2"); client.Authenticator = OAuth1Authenticator.ForProtectedResource(ConsumerKey, ConsumerSecret, GAccessToken, AccessTokenSecret); var request = new RestRequest("/user/friends"); request.AddParameter("userId", UserId,ParameterType.GetOrPost); // request.AddParameter("category", "all",ParameterType.GetOrPost); client.ExecuteAsync(request, response => { TreatFreindsList(); }); And that’s it now we can access all OAuth methods using RestSharp.

    Read the article

  • How to make this design closer to proper DDD?

    - by Seralize
    I've read about DDD for days now and need help with this sample design. All the rules of DDD make me very confused to how I'm supposed to build anything at all when domain objects are not allowed to show methods to the application layer; where else to orchestrate behaviour? Repositories are not allowed to be injected into entities and entities themselves must thus work on state. Then an entity needs to know something else from the domain, but other entity objects are not allowed to be injected either? Some of these things makes sense to me but some don't. I've yet to find good examples of how to build a whole feature as every example is about Orders and Products, repeating the other examples over and over. I learn best by reading examples and have tried to build a feature using the information I've gained about DDD this far. I need your help to point out what I do wrong and how to fix it, most preferably with code as "I would not recomment doing X and Y" is very hard to understand in a context where everything is just vaguely defined already. If I can't inject an entity into another it would be easier to see how to do it properly. In my example there are users and moderators. A moderator can ban users, but with a business rule: only 3 per day. I did an attempt at setting up a class diagram to show the relationships (code below): interface iUser { public function getUserId(); public function getUsername(); } class User implements iUser { protected $_id; protected $_username; public function __construct(UserId $user_id, Username $username) { $this->_id = $user_id; $this->_username = $username; } public function getUserId() { return $this->_id; } public function getUsername() { return $this->_username; } } class Moderator extends User { protected $_ban_count; protected $_last_ban_date; public function __construct(UserBanCount $ban_count, SimpleDate $last_ban_date) { $this->_ban_count = $ban_count; $this->_last_ban_date = $last_ban_date; } public function banUser(iUser &$user, iBannedUser &$banned_user) { if (! $this->_isAllowedToBan()) { throw new DomainException('You are not allowed to ban more users today.'); } if (date('d.m.Y') != $this->_last_ban_date->getValue()) { $this->_ban_count = 0; } $this->_ban_count++; $date_banned = date('d.m.Y'); $expiration_date = date('d.m.Y', strtotime('+1 week')); $banned_user->add($user->getUserId(), new SimpleDate($date_banned), new SimpleDate($expiration_date)); } protected function _isAllowedToBan() { if ($this->_ban_count >= 3 AND date('d.m.Y') == $this->_last_ban_date->getValue()) { return false; } return true; } } interface iBannedUser { public function add(UserId $user_id, SimpleDate $date_banned, SimpleDate $expiration_date); public function remove(); } class BannedUser implements iBannedUser { protected $_user_id; protected $_date_banned; protected $_expiration_date; public function __construct(UserId $user_id, SimpleDate $date_banned, SimpleDate $expiration_date) { $this->_user_id = $user_id; $this->_date_banned = $date_banned; $this->_expiration_date = $expiration_date; } public function add(UserId $user_id, SimpleDate $date_banned, SimpleDate $expiration_date) { $this->_user_id = $user_id; $this->_date_banned = $date_banned; $this->_expiration_date = $expiration_date; } public function remove() { $this->_user_id = ''; $this->_date_banned = ''; $this->_expiration_date = ''; } } // Gathers objects $user_repo = new UserRepository(); $evil_user = $user_repo->findById(123); $moderator_repo = new ModeratorRepository(); $moderator = $moderator_repo->findById(1337); $banned_user_factory = new BannedUserFactory(); $banned_user = $banned_user_factory->build(); // Performs ban $moderator->banUser($evil_user, $banned_user); // Saves objects to database $user_repo->store($evil_user); $moderator_repo->store($moderator); $banned_user_repo = new BannedUserRepository(); $banned_user_repo->store($banned_user); Should the User entitity have a 'is_banned' field which can be checked with $user->isBanned();? How to remove a ban? I have no idea.

    Read the article

  • Deleted Myself from Admin Group - Now Getting Error usermod: cannot lock /etc/passwd; try again later

    - by BubbaJ
    I have a laptop with Ubuntu 11.10 that is shared between myself and two other family members. My user id was setup as the only "Administrator" on the laptop. The other users were setup as "Standard" users. In my attempt to try to add myself to the user groups for the other users, I somehow deleted myself from the admin groups. I used the "usermod" command from the terminal. I must have neglected to include the proper switches or syntax for the update. It looks like I successfully added my userid to the group associated with my wife's account. When I use the "groups" command, I can see only my id and my wife's id in the list. I no longer see the "admin" or "adm" groups, and others that used to be listed. When I go into System Settings User Accounts it looks like my ID is now listed as a "Standard" user. I would like to change my account back to "Administrator", but now I can't. I did some searches for solutions and found that I would need to boot into Recovery Mode and execute the usermod command from the root session. I was able to successfully boot into Recovery Mode and get to the root session. I was trying to execute the command "usermod -a -G admin user1" to add my id (user1) back to the admin group. When I execute the command from the root session, I get the error message "usermod: cannot lock /etc/passwd; try again later". I tried preceding the usermod command with "sudo", but it didn't make a difference, same error. I then tried adding a new user using adduser, thinking I would try to create a new userid and make the new userid part of the admin group. I get the same error using the adduser command. I saw some posts that recommend looking for and deleting files that end in ".lock" in the etc directory. The only file I found was .pwd.lock which I haven't touched. I am at a loss as to what to try next. I am relatively inexperienced with Ubuntu and Linux, so alot of this is new to me. Any help you can provide would be much appreciated.

    Read the article

  • How to use NSMutableDictionary to store and retrieve data

    - by TechFusion
    I have created Window Based application and tab bar controller as root controller. My objective is to store Text Field data values in one tab bar VC and will be accessible and editable by other VC and also retrievable when application start. I am looking to use NSMutableDictionary class in AppDelegate so that I can access stored Data Values with keys. //TestAppDelegate.h extern NSString *kNamekey ; extern NSString *kUserIDkey ; extern NSString *kPasswordkey ; @interface TestAppDelegate :NSObject{ UIWindow *window; IBOutlet UITabBarController *rootController; NSMutableDictionary *outlineData ; } @property(nonatomic,retain)IBOutlet UIWindow *window; @property(nonatomic,retain)IBOutlet UITabBarController *rootController; @property(nonatomic,retain) NSMutableDictionary *outlineData ; @end //TestAppDelegate.m import "TestAppDelegate.h" NSString *kNamekey =@"Namekey"; NSString *kUserIDkey =@"UserIDkey"; NSString *kPasswordkey =@"Passwordkey"; @implemetation TestAppDelegate @synthesize outlineData ; -(void)applicationDidFinishLaunching:(UIApplication)application { NSMutableDictionary *tempMutableCopy = [[[NSUserDefaults standardUserDefaults] objectForKey:kRestoreLocationKey] mutableCopy]; self.outlineData = tempMutableCopy; [tempMutableCopy release]; if(outlineData == nil){ NSString *NameDefault = NULL; NSString *UserIDdefault= NULL; NSString *Passworddefault= NULL; NSMutableDictionary *appDefaults = [NSMutableDictionary dictionaryWithObjectsAndKeys: NameDefault, kNamekey , UserIDdefault, kUserIDkey , Passworddefault, kPasswordkey , nil]; self.outlineData = appDefaults; [appDefaults release]; } [window addSubview:rootController.view]; [window makeKeyAndVisible]; NSMutableDictionary *savedLocationDict = [NSMutableDictionary dictionaryWithObject:outlineData forKey:kRestoreLocationKey]; [[NSUserDefaults standardUserDefaults] registerDefaults:savedLocationDict]; [[NSUserDefaults standardUserDefaults] synchronize]; } -(void)applicationWillTerminate:(UIApplication *)application { [[NSUserDefaults standardUserDefaults] setObject:outlineData forKey:kRestoreLocationKey]; } @end Here ViewController is ViewController of Navigation Controller which is attached with one tab bar.. I have attached xib file with ViewController //ViewController.h @interface IBOutlet UITextField *Name; IBOutlet UITextField *UserId; IBOutlet UITextField *Password; } @property(retain,nonatomic) IBOutlet UITextField *Name @property(retain,nonatomic) IBOutlet UITextField *UserId; @property(retain,nonatomic) IBOutlet UITextField *Password; -(IBAction)Save:(id)sender; @end Here in ViewController.m, I am storing object values with keys. /ViewController.m -(IBAction)Save:(id)sender{ TestAppDelegate appDelegate = (TestAppDelegate)[[UIApplication sharedApplication] delegate]; [appDelegate.outlineData setObject:Name.text forKey:kNamekey ]; [appDelegate.outlineData setObject:UserId.text forKey:kUserIDkey ]; [appDelegate.outlineData setObject:Password.text forKey:kPasswordkey]; [[NSUserDefaults standardUserDefaults] synchronize]; } I am accessing stored object using following method. -(void)loadData { TabBarAppDelegate *appDelegate = (TabBarAppDelegate *)[[UIApplication sharedApplication] delegate]; Name = [appDelegate.outlineData objectForKey:kNamekey ]; UserId = [appDelegate.outlineData objectForKey:kUserIDkey ]; Password = [appDelegate.outlineData objectForKey:kPasswordkey]; [Name release]; [UserId release]; [Password release]; } I am getting EXEC_BAD_ACCESS in application. Where I am making mistake ? Thanks,

    Read the article

  • Converting AES encryption token code in C# to php

    - by joey
    Hello, I have the following .Net code which takes two inputs. 1) A 128 bit base 64 encoded key and 2) the userid. It outputs the AES encrypted token. I need the php equivalent of the same code, but dont know which corresponding php classes are to be used for RNGCryptoServiceProvider,RijndaelManaged,ICryptoTransform,MemoryStream and CryptoStream. Im stuck so any help regarding this would be really appreciated. using System; using System.Text; using System.IO; using System.Security.Cryptography; class AESToken { [STAThread] static int Main(string[] args) { if (args.Length != 2) { Console.WriteLine("Usage: AESToken key userId\n"); Console.WriteLine("key Specifies 128-bit AES key base64 encoded supplied by MediaNet to the partner"); Console.WriteLine("userId specifies the unique id"); return -1; } string key = args[0]; string userId = args[1]; StringBuilder sb = new StringBuilder(); // This example code uses the magic string “CAMB2B”. The implementer // must use the appropriate magic string for the web services API. sb.Append("CAMB2B"); sb.Append(args[1]); // userId sb.Append('|'); // pipe char sb.Append(System.DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ssUTC")); //timestamp Byte[] payload = Encoding.ASCII.GetBytes(sb.ToString()); byte[] salt = new Byte[16]; // 16 bytes of random salt RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); rng.GetBytes(salt); // the plaintext is 16 bytes of salt followed by the payload. byte[] plaintext = new byte[salt.Length + payload.Length]; salt.CopyTo(plaintext, 0); payload.CopyTo(plaintext, salt.Length); // the AES cryptor: 128-bit key, 128-bit block size, CBC mode RijndaelManaged cryptor = new RijndaelManaged(); cryptor.KeySize = 128; cryptor.BlockSize = 128; cryptor.Mode = CipherMode.CBC; cryptor.GenerateIV(); cryptor.Key = Convert.FromBase64String(args[0]); // the key byte[] iv = cryptor.IV; // the IV. // do the encryption ICryptoTransform encryptor = cryptor.CreateEncryptor(cryptor.Key, iv); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write); cs.Write(plaintext, 0, plaintext.Length); cs.FlushFinalBlock(); byte[] ciphertext = ms.ToArray(); ms.Close(); cs.Close(); // build the token byte[] tokenBytes = new byte[iv.Length + ciphertext.Length]; iv.CopyTo(tokenBytes, 0); ciphertext.CopyTo(tokenBytes, iv.Length); string token = Convert.ToBase64String(tokenBytes); Console.WriteLine(token); return 0; } } Please help. Thank You.

    Read the article

< Previous Page | 10 11 12 13 14 15 16 17 18 19 20 21  | Next Page >