Thursday, December 8, 2011

Setting NTFS Permissions with C# Programmatically

Reference the dll, and use it.
using Microsoft.Win32.Security;
Here's a method to add a dir, and set NTFS permissions on it for a given user:
private Boolean CreateDir(String strSitePath, String strUserName) {
       Boolean bOk;
       try {
              Directory.CreateDirectory(strSitePath);
              SecurityDescriptor secDesc = SecurityDescriptor.GetFileSecurity(strSitePath, SECURITY_INFORMATION.DACL_SECURITY_INFORMATION);
              Dacl dacl = secDesc.Dacl;
              Sid sidUser = new Sid (strUserName);
 
              // allow: folder, subfolder and files
              // modify
              dacl.AddAce (new AceAccessAllowed (sidUser, AccessType.GENERIC_WRITE | AccessType.GENERIC_READ | AccessType.DELETE | AccessType.GENERIC_EXECUTE , AceFlags.OBJECT_INHERIT_ACE | AceFlags.CONTAINER_INHERIT_ACE));
             
              // deny: this folder
              // write attribs
              // write extended attribs
              // delete
              // change permissions
              // take ownership
              DirectoryAccessType DAType = DirectoryAccessType.FILE_WRITE_ATTRIBUTES | DirectoryAccessType.FILE_WRITE_EA | DirectoryAccessType.DELETE | DirectoryAccessType.WRITE_OWNER | DirectoryAccessType.WRITE_DAC;
              AccessType AType = (AccessType)DAType;
              dacl.AddAce (new AceAccessDenied (sidUser, AType));
 
              secDesc.SetDacl(dacl);
              secDesc.SetFileSecurity(strSitePath, SECURITY_INFORMATION.DACL_SECURITY_INFORMATION);
              bOk = true;
       } catch {
              bOk = false;
       }
       return bOk;
} /* CreateDir */

The AceFlags determine the level of inheritance on the object.
And the DirectoryAccessType is used to create a AccessType with some permissions not in the AccessType enum.
I hope this is useful.

Monday, November 28, 2011

iPhone – Set or change title of UIBarButtonItem


self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"TITLE GOES HERE" style:UIBarButtonItemStyleBordered target:self action:@selector(functionToCallOnClick)];

Thursday, November 17, 2011

SQL - Get All Columns in a Table That Contains NULL

declare @col varchar(255), @cmd varchar(max)

DECLARE getinfo cursor for
SELECT c.name FROM sys.tables t JOIN sys.columns c ON t.Object_ID = c.Object_ID
WHERE t.Name = 'ADDR_Address'

OPEN getinfo

FETCH NEXT FROM getinfo into @col

WHILE @@FETCH_STATUS = 0
BEGIN
    SELECT @cmd = 'IF NOT EXISTS (SELECT top 1 * FROM ADDR_Address WHERE [' + @col + '] IS NOT NULL) BEGIN print ''' + @col + ''' end'
    EXEC(@cmd)

    FETCH NEXT FROM getinfo into @col
END

CLOSE getinfo
DEALLOCATE getinfo
Where 'ADDR_Address' is table name

Friday, November 11, 2011

Redirect All Request to Another URL Programmatically

The following code samples configure the Default Web Site to redirect all requests to "http://www.contoso.com" using an HTTP 302 status code.



using System;
using System.Text;
using Microsoft.Web.Administration;

internal static class Sample
{
   private static void Main()
   {
      using (ServerManager serverManager = new ServerManager())
      {
         Configuration config = serverManager.GetWebConfiguration("Default Web Site");

         ConfigurationSection httpRedirectSection = config.GetSection("system.webServer/httpRedirect");
         httpRedirectSection["enabled"] = true;
         httpRedirectSection["destination"] = @"http://www.contoso.com";
         httpRedirectSection["exactDestination"] = false;
         httpRedirectSection["httpResponseStatus"] = @"Found";

         serverManager.CommitChanges();
      }
   }
}

HTTP Redirection in IIS 7 on Windows Server 2008

HTTP Redirection in IIS 7 on Windows Server 2008: "HTTP Redirection in IIS 7 on Windows Server 2008"

Redirect HTTP to HTTPS with IIS 7 | IIS Aid

Redirect HTTP to HTTPS with IIS 7

Friday, October 21, 2011

Wednesday, October 5, 2011

How to forward localhost IP-Address to an Android Emulator


Each emulator instance provides a control console the you can connect to, to issue commands that are specific to that instance. You can use the redir console command to set up redirections as needed for an emulator instance.

First, determine the console port number for the target emulator instance. For example, the console port number for the first emulator instance launched is 5554. Next, connect to the console of the target emulator instance, specifying its console port number, as follows:

telnet localhost 5554

Example:

Assume that your environment is
A is you development machine
B is your first emulator instance, running on A

Set up the server on B, listening to 10.0.2.15:<serverPort>
On B's console, set up a redirection from A:localhost:<localPort> to B:10.0.2.15:<serverPort>

* 10.0.2.15 is the default Ip Address of the Emulator
** For Windows: All Commands must be written in "Windows Command Prompt"

Tuesday, October 4, 2011

How to use alias in the WHERE or GROUP BY clause

One workaround would be to use a derived table:



select *
from 
   (
   select a + b as aliased_column
   from table
   ) dtwhere dt.aliased_column = something.

Add Code Syntax Highlighter To your Blog

A very tutorial on how to add code Highlighter to your Blogger's account.

http://heisencoder.net/2009/01/adding-syntax-highlighting-to-blogger.html

Thursday, September 29, 2011

Android - How To Make 2 or More Emulator Communicate Each Other


Each emulator instance provides a control console the you can connect to, to issue commands that are specific to that instance. You can use the redir console command to set up redirections as needed for an emulator instance.

First, determine the console port number for the target emulator instance. For example, the console port number for the first emulator instance launched is 5554. Next, connect to the console of the target emulator instance, specifying its console port number, as follows:

telnet localhost 5554

Once connected, use the redir command to work with redirections. To add a redirection, use:.

redir add <protocol>:<host-port>:<guest-port>

where <protocol> is either tcp or udp, and <host-port> and <guest-port> sets the mapping between your own machine and the emulated system, respectively.

For example, the following command sets up a redirection that will handle all incoming TCP connections to your host (development) machine on 127.0.0.1:5000 and will pass them through to the emulated system's 10.0.2.15:6000.:

redir add tcp:5000:6000

Or UDP
redir add udp:5000:6000


Example:

Assume that your environment is

A is you development machine
B is your first emulator instance, running on A
C is your second emulator instance, running on A too
and you want to run a server on B, to which C will connect, here is how you could set it up:

Set up the server on B, listening to 10.0.2.15:<serverPort>
On B's console, set up a redirection from A:localhost:<localPort> to B:10.0.2.15:<serverPort>
On C, have the client connect to 10.0.2.2:<localPort>


** For Windows All commands must be written in a "Windows Command Prompt"

Monday, September 26, 2011

Android - HttpPost

/**
* Reads data from the data reader and posts it to a server via POST request.
* data - The data you want to send
* endpoint - The server's address
* output - writes the server's response to output
* @throws Exception
*/
public static void postData(Reader data, URL endpoint, Writer output) throws Exception
{
HttpURLConnection urlc = null;
try
{
urlc = (HttpURLConnection) endpoint.openConnection();
try
{
urlc.setRequestMethod("POST");
} catch (ProtocolException e)
{
throw new Exception("Shouldn't happen: HttpURLConnection doesn't support POST??", e);
}
urlc.setDoOutput(true);
urlc.setDoInput(true);
urlc.setUseCaches(false);
urlc.setAllowUserInteraction(false);
urlc.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8");
OutputStream out = urlc.getOutputStream();
try
{
Writer writer = new OutputStreamWriter(out, "UTF-8");
pipe(data, writer);
writer.close();
} catch (IOException e)
{
throw new Exception("IOException while posting data", e);
} finally
{
if (out != null)
out.close();
}
InputStream in = urlc.getInputStream();
try
{
Reader reader = new InputStreamReader(in);
pipe(reader, output);
reader.close();
} catch (IOException e)
{
throw new Exception("IOException while reading response", e);
} finally
{
if (in != null)
in.close();
}
} catch (IOException e)
{
throw new Exception("Connection error (is server running at " + endpoint + " ?): " + e);
} finally
{
if (urlc != null)
urlc.disconnect();
}
}
/**
* Pipes everything from the reader to the writer via a buffer
*/
private static void pipe(Reader reader, Writer writer) throws IOException
{
char[] buf = new char[1024];
int read = 0;
while ((read = reader.read(buf)) >= 0)
{
writer.write(buf, 0, read);
}
writer.flush();
}

Sends an HTTP GET request to a url

/**
* Sends an HTTP GET request to a url
*
* @param endpoint - The URL of the server. (Example: " http://www.yahoo.com/search")
* @param requestParameters - all the request parameters (Example: "param1=val1¶m2=val2"). Note: This method will add the question mark (?) to the request - DO NOT add it yourself
* @return - The response from the end point
*/
public static String sendGetRequest(String endpoint, String requestParameters)
{
String result = null;
if (endpoint.startsWith("http://"))
{
// Send a GET request to the servlet
try
{
// Send data
String urlStr = endpoint;
if (requestParameters != null && requestParameters.length () > 0)
{
urlStr += "?" + requestParameters;
}
URL url = new URL(urlStr);
URLConnection conn = url.openConnection ();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = rd.readLine()) != null)
{
sb.append(line);
}
rd.close();
result = sb.toString();
} catch (Exception e)
{
e.printStackTrace();
}
}
return result;
}

Saturday, September 24, 2011

Android - Stop/Disable Orientation

Add the Following Lines:

In AndroidManifest.xml


Find the Activity section in which you want stop/disable the orientation and add the following attribute


android:configChanges="keyboardHidden|orientation"


In the Activity(In which you want to stop/disable orientation) class add the following code:



@Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

RESTful Webservice

RESTful Webservice:

What is REST?
REST is a term coined by Roy Fielding in his Ph.D. dissertation to describe an architecture style of networked systems. REST is an acronym standing for Representational State Transfer. Here is Roy Fielding's explanation of the meaning of Representational State Transfer:

"Representational State Transfer is intended to evoke an image of how a well-designed Web application behaves: a network of web pages (a virtual state-machine), where the user progresses through an application by selecting links (state transitions), resulting in the next page (representing the next state of the application) being transferred to the user and rendered for their use."

What is RESTful webservice?
REST is not a standard. Its just an architectural style. While REST is not a standard, it does use standards:

. HTTP
. URL
. XML/HTML/GIF/JPEG/etc (Resource Representations)
. text/xml, text/html, image/gif, image/jpeg, etc (MIME Types)

REST Web Services Characteristics:

Client-Server: a pull-based interaction style: consuming components pull representations.
Stateless: each request from client to server must contain all the information necessary to understand the request, and cannot take advantage of any stored context on the server.
Cache: to improve network efficiency responses must be capable of being labeled as cacheable or non-cacheable.
Uniform interface: all resources are accessed with a generic interface (e.g., HTTP GET, POST, PUT, DELETE).
Named resources: the system is comprised of resources which are named using a URL.
Interconnected resource representations: the representations of the resources are interconnected using URLs, thereby enabling a client to progress from one state to another.
Layered components: intermediaries, such as proxy servers, cache servers, gateways, etc, can be inserted between clients and resources to support performance, security, etc.

Principles of REST Web Service Design
  • The key to creating Web Services in a REST network (i.e., the Web) is to identify all of the conceptual entities that you wish to expose as services. Above we saw some examples of resources: parts list, detailed part data, purchase order.
  • Create a URL to each resource. The resources should be nouns, not verbs. For example, do not use this:
               http://www.parts-depot.com/parts/getPart?id=00345
               Note the verb, getPart. Instead, use a noun:
               http://www.parts-depot.com/parts/00345
  • Categorize your resources according to whether clients can just receive a representation of the resource, or whether clients can modify (add to) the resource. For the former, make those resources accessible using an HTTP GET. For the later, make those resources accessible using HTTP POST, PUT, and/or DELETE.
  • All resources accessible via HTTP GET should be side-effect free. That is, the resource should just return a representation of the resource. Invoking the resource should not result in modifying the resource.
  • No man/woman is an island. Likewise, no representation should be an island. In other words, put hyperlinks within resource representations to enable clients to drill down for more information, and/or to obtain related information.
  • Design to reveal data gradually. Don't reveal everything in a single response document. Provide hyperlinks to obtain more details.
  • Specify the format of response data using a schema (DTD, W3C Schema, RelaxNG, or Schematron). For those services that require a POST or PUT to it, also provide a schema to specify the format of the response.
  • Describe how your services are to be invoked using either a WSDL document, or simply an HTML document.

Wednesday, September 21, 2011

Android - Accessing Your Preference From Hardware Menu Button


1) Create New XML File By Clicking "File->New->Other->Android XML File.
2) In Newly Open Dialog Box:
   a) File = Name of Your Preference File Name
   b) "In What type Of Resource would you like to create?" Select "PREFERENCE"
   c) Don't Change The Folder Path
   d) "In Select the root element for XML File" Select "PREFERENCESCREEN"
   e) Click Finish.

3) Select The Type of Preference You want to add. All with very good exmaples are shown here
   http://www.kaloer.com/android-preferences

4) In "AndroidManifest.xml" add the following segment
   <activity
        android:name=".Name_of_your_preference_file">
   </activity>

5) Add New Activity which extends from PreferenceAcivity
   *To know how to add new activity take a look here
    http://codersapprentice.blogspot.com/2011/09/android-easiest-way-to-add-new-activity.html

6) In OnCreate function of the newly created Activity Add the following lines
   
    addPreferencesFromResource(R.xml.mypeference);//Your Preference XML Resource
    PreferenceManager.setDefaultValues(ApplicationPreference.this, R.xml.mypeference, false);//To Set Default Values

7) To Call Preference Screen From Hardware Menu Button Add the following code on the activity from which you want to call the preference:
   @Override
    public boolean onKeyDown(int keycode, KeyEvent event)
    {
    if(keycode == KeyEvent.KEYCODE_MENU)
    {    
    Intent settingsActivity = new Intent(getApplicationContext(),ApplicationPreference.class);
    startActivity(settingsActivity);
    }
    return super.onKeyDown(keycode,event);
    }

Android: Hardware Menu button click event

The easiest way is to capture the onKeyDown event for the menu button click:



@Override
public boolean onKeyDown(int keycode, KeyEvent event ) {
 if(keycode == KeyEvent.KEYCODE_MENU)
{
  AlertDialog.Builder dialogBuilder
  = new AlertDialog.Builder(this)
  .setMessage("Test")
  .setTitle("Menu dialog");
  dialogBuilder.create().show();
 }
 return super.onKeyDown(keycode,event); 
}