Add New Style To Google Docs

In order to enable it you need to create a new script: Tools >> Script Editor>> New and paste the code there. Then you will have to authorize the script and reload the document so that the menu appears on in the menu bar. Then select a patch of text and pick Extras >> Apply code style. The following code snippet was taken from here- http://pastebin.com/4pNBJ9pC

// is called by google docs when a document is open
// adds a menu with a menu item that applies a style to the currently selected text
function onOpen() {
  DocumentApp.getUi()
  .createMenu('Extras')
  .addItem('Apply code style', 'applyCodeStyle')
  .addToUi();
}
 
// definition of a style to be applied
var style = {
  bold: false,
  backgroundColor: "#DDDDDD",
  fontFamily: DocumentApp.FontFamily.CONSOLAS
};
 
// helper function that strips the selected element and passes it to a handler
function withElement(processPartial, processFull) {
  var selection = DocumentApp.getActiveDocument().getSelection();
  if (selection) {
    var elements = selection.getSelectedElements();
    for (var i = 0; i < elements.length; i++) {
      var element = elements[i];
      if (element.getElement().editAsText) {
        var text = element.getElement();
        if (element.isPartial()) {
          var from = element.getStartOffset();
          var to = element.getEndOffsetInclusive();
          return processPartial(element, text, from, to);
        } else {
          return processFull(element, text);
        }
      }
    }
  }
}
 
// called in response to the click on a menu item
function applyCodeStyle() {
  return withElement(
    applyPartialStyle.bind(this, style),
    applyFullStyle.bind(this, style)
  );
}
 
// applies the style to a selected text range
function applyPartialStyle(style, element, text, from, to) {
  text.setFontFamily(from, to, style.fontFamily);
  text.setBackgroundColor(from, to, style.backgroundColor);
  text.setBold(from, to, style.bold);
}
 
// applies the style if the entire element is selected
function applyFullStyle(style, element, text) {
  text.setFontFamily(style.fontFamily);
  text.setBackgroundColor(style.backgroundColor);
  text.setBold(style.bold);
}
Advertisements

WebRequest From WinForm Application

private void btnSave_Click(object sender, EventArgs e)
{
    try
    {

        btnSave.Enabled = false;

        String filePath = txtVoiceFileName.Text;

        // Create a request using a URL that can receive a post. 
        WebRequest request = WebRequest.Create("http://182.161.999.111:2022/Home/ReceiveAudio/");
        // Set the Method property of the request to POST.
        request.Method = "POST";
        // Create POST data and convert it to a byte array.
        // string postData = "This is a test that posts this string to a Web server.";


        NameValueCollection outgoingQueryString = HttpUtility.ParseQueryString(String.Empty);
        outgoingQueryString.Add("CustomerName", txtCustomerName.Text.Trim() );
        outgoingQueryString.Add("ContactNumber", txtMsisdn.Text.Trim());
           


        string postData = outgoingQueryString.ToString();

        byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        // Set the ContentType property of the WebRequest.
        request.ContentType = "application/x-www-form-urlencoded";
        // Set the ContentLength property of the WebRequest.
        request.ContentLength = byteArray.Length;
        // Get the request stream.
        Stream dataStream = request.GetRequestStream();
        // Write the data to the request stream.
        dataStream.Write(byteArray, 0, byteArray.Length);
        // Close the Stream object.
        dataStream.Close();
        // Get the response.
        WebResponse response = request.GetResponse();
        // Display the status.
        Console.WriteLine(((HttpWebResponse)response).StatusDescription);
        // Get the stream containing content returned by the server.
        dataStream = response.GetResponseStream();
        // Open the stream using a StreamReader for easy access.
        StreamReader reader = new StreamReader(dataStream);
        // Read the content.
        string responseFromServer = reader.ReadToEnd();
        // Display the content.
        Console.WriteLine(responseFromServer);
        MessageBox.Show(responseFromServer);
        // Clean up the streams.
        reader.Close();
        dataStream.Close();
        response.Close();

        // String filePath = txtVoiceFileName.Text;
        var FileUploadResponse = WebHelper.MakeRequest("http://182.160.99.115:2022/Home/UploadAudio/",
                            new
                            {
                                wavFile = new FileInfo(filePath)
                                //Test = "Hello"
                                //File1 = new UploadFile(@"text\plain", "file1.txt", new MemoryStream(Encoding.UTF8.GetBytes("Hello World"))),
                                //File2 = new FileInfo("MyFile.txt")
                            });
        var FileUploadResult = FileUploadResponse.ResultToString();

    }
    catch (Exception Ex)
    {
        MessageBox.Show(Ex.Message);                
    }
    finally { btnSave.Enabled = true; }
}



//===============================================

[HttpPost]
public JsonResult ReceiveAudio(FormCollection data)
{
    try
    {
        string CustomerName = data["CustomerName"].ToString();
        string ContactNumber = data["ContactNumber"].ToString();
        string IsNewSimActivation = data["IsNewSimActivation"].ToString();
        string IsSimReplacement = data["IsSimReplacement"].ToString();
        string IsRv = data["IsRv"].ToString();
        string IsDataActivation = data["IsDataActivation"].ToString();
        string IsDeviceOffers = data["IsDeviceOffers"].ToString();
        string IsVas = data["IsVas"].ToString();
        string IsCampMsg = data["IsCampMsg"].ToString();
        string CashReceived = data["CashReceived"].ToString();
        string IsEasyLoad = data["IsEasyLoad"].ToString();
        string VoiceFileName = data["VoiceFileName"].ToString();

        string ConnectionString = WebConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

           

        return Json("Success");
    }
    catch (Exception Ex)
    {
        return Json("Server says:" + Ex.Message, JsonRequestBehavior.AllowGet);

    }
}

Configure ASP.NET MVC To Accept Large File Uploading

///
///In Web.config
///

<configuration>
    <appSettings>
       ...
    </appSettings>
  

    <system.web>
        <compilation debug="true" targetFramework="4.5"/>
        <httpRuntime targetFramework="4.5"
                     executionTimeout="1000"
                     maxRequestLength="214748364"
                     useFullyQualifiedRedirectUrl="false"
                     minFreeThreads="8"
                     minLocalRequestFreeThreads="4"
                     appRequestQueueLimit="100" />
    </system.web>

    <system.webServer>
        <validation validateIntegratedModeConfiguration="false" />
        <handlers>
            <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
            <remove name="OPTIONSVerbHandler" />
            <remove name="TRACEVerbHandler" />
            <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
        </handlers>

        <security>
            <requestFiltering>
                <requestLimits maxAllowedContentLength="1073741824" />
            </requestFiltering>
        </security>
    </system.webServer>

    <connectionStrings>
        ....
    </connectionStrings> 
</configuration>
///
/// In Controller
///

[ValidateInput(false)]
[HttpPost]
public JsonResult UploadAudio()
{
    try
    {
        foreach (string f in Request.Files.AllKeys)
        {
            var file = Request.Files[f];

            var path = HttpContext.Server.MapPath("~/Voices");
            if (!System.IO.File.Exists(System.IO.Path.Combine(path, file.FileName)))
            {
                file.SaveAs(System.IO.Path.Combine(path, file.FileName));
            }
        }

        return Json("success");
    }
    catch (Exception Ex)
    {
        return Json("Server says:" + Ex.Message, JsonRequestBehavior.AllowGet);
    }
}

ASP.NET MVC RedirectToAction() With Query String

public ActionResult Index()
{
    //If no area
    return RedirectToAction("ActionMethod", "Controller", new { userid=5, name="Five"}); 

   //If area
    return RedirectToAction("ActionMethod", "Controller", new { area = "AreaName", userid = 5, name = "Five" });

}


//Redirected Action Method
public ActionResult Index(int userid, string name)
{
    return View();
}

//OR
public ActionResult Index()
{
    int userId  = Convert.ToInt32(Request.QueryString["userid"]);
    String name = Request.QueryString["name"];
    return View();
}

HTML Radio Button & JQuery

 <input type="radio" name="ABC" value="a b c" />
 <input type="radio" name="ABC" value="x y z" />
var radioValue=  $('input[type=radio][name=ABC]:checked').val();
               
if (typeof radioValue=='undefined') {
    alert('Please select ...');
    return;
}

Working With ION In Android

//
//Android Code
//


//Manifest
<uses-permission android:name="android.permission.INTERNET"/>

//build.gradle (Module:app)
dependencies {
    ...
    compile group: 'com.koushikdutta.ion', name: 'ion', version: '2.1.6'
}

//MainActivity.java
    public void SubmitData(View view){

        JsonObject json = new JsonObject();
        json.addProperty("foo", "bar");
        json.addProperty("bar", "foo");
        try
        {
            Ion.with(getApplicationContext())
                    .load("http://182.160.99.115:1012/Home/SubmitData")
                    .setJsonObjectBody(json)
                    .asJsonObject()
                    .setCallback(new FutureCallback<JsonObject>() {
                        @Override
                        public void onCompleted(Exception e, JsonObject result) {

                         String ServerSaid =  result.get("serversay").getAsString();

                            Toast.makeText(getApplicationContext(),ServerSaid,Toast.LENGTH_LONG).show();
                        }
                    });

        }
        catch (Exception ex ){
            Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
        }
    }
//
//ASP.NET MVC Code
//


namespace WorkingWithIon.Controllers
{
    public class HomeController : Controller
    {     
        public JsonResult SubmitData(string foo, string bar)
        {
            return Json(new{serversay=foo + " and " + bar}, JsonRequestBehavior.AllowGet);
        }
    }
}

Working with Camera in Android

//
//Taking a photo using camera, save in default camera location and show in ImageView 
control-
//

<uses-feature
        android:name="android.hardware.camera"
        android:required="true" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="ANDROID.PERMISSION.READ_EXTERNAL_STORAGE" />

public void TakePhoto(View view)
{
    Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(imageIntent, REQUEST_IMAGE_CAPTURE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK)
    {
        Bundle bundle = data.getExtras();
        Bitmap bitmap = (Bitmap) bundle.get("data");

        ImageView imageView=(ImageView)findViewById(R.id.ivPhoto);
        imageView.setImageBitmap(bitmap);
    }
}

//
//Display photo from default Camera directory with a given name in an ImageView 
//

//Modify manifest file
<uses-feature
        android:name="android.hardware.camera"
        android:required="true" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="ANDROID.PERMISSION.READ_EXTERNAL_STORAGE" />

//Modify build.gradle(Module:app) as follows-
compile 'com.squareup.picasso:picasso:2.5.2'

public void ShowPhoto(View view)
{
    EditText PhotoNameTextbox=(EditText)findViewById(R.id.txtPhotoName);
    String PhotoName= PhotoNameTextbox.getText().toString() + ".jpg";

    //Get default camera directory
    File CameraDirectory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString(), "Camera"); // DIRECTORY_PICTURES

    //Photo path
    File photoFile= new File(CameraDirectory + File.separator + PhotoName);

    if (photoFile.exists())
    {
        ImageView imageView=(ImageView)findViewById(R.id.ivPhoto);

       //Following lines can be another option to show photo. Currently not required.
       /*Bitmap bitmap = BitmapFactory.decodeFile(photoFile.getAbsolutePath());
        imageView.setImageBitmap(bitmap);*/

       //Picasso is a third party library. http://square.github.io/picasso/
       Picasso.with(getApplicationContext()).load(photoFile).fit()
              .centerCrop().into(imageView);

    }
    else
    {
       Toast.makeText(DisplayPhoto.this, "Photo not found", Toast.LENGTH_SHORT).show();
     }
}

//
//Take a photo, Save with custom name, then display in ImageView
//

//Modify manifest file
<uses-feature
        android:name="android.hardware.camera"
        android:required="true" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="ANDROID.PERMISSION.READ_EXTERNAL_STORAGE" />

//Modify build.gradle(Module:app) as follows-
compile 'com.squareup.picasso:picasso:2.5.2'

public class TakePhotoAndSaveWithCustomNameAndPath extends AppCompatActivity
{
    File CameraDirectory;
    String photoName;
    static final int REQUEST_IMAGE_CAPTURE = 101;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_take_photo_and_save_with_custom_name_and_path);
        CameraDirectory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).toString(), "Camera");
    }
    
    public void TakePhoto(View view){
        Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        
        photoName = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        Log.d("CustomPhotoName",photoName);
        File photo = new File(CameraDirectory, photoName + ".jpg");
        Uri uriSavedImage = Uri.fromFile(photo);
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
        startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {

            try{
                ImageView imageView=(ImageView)findViewById(R.id.imageviewImage);
                File photo = new File(CameraDirectory, photoName + ".jpg");
                if(photo.exists()){
                    //Picasso is a third party library. http://square.github.io/picasso/
                    Picasso.with(getApplicationContext()).load(photo).fit().centerCrop().into(imageView);
                }
                else{
                    Log.d("PhotoFileStatus","Not found");
                }
            }
            catch (Exception ex){
                Log.d("PhotoError",ex.getMessage().toString());
                Toast.makeText(TakePhotoAndSaveWithCustomNameAndPath.this, ex.getMessage().toString(), Toast.LENGTH_LONG).show();
            }

        }
    }
}