public IntPtr LookupContactByName(string name, ContentResolver cr) { IntPtr handle = IntPtr.Zero; ICursor cur = cr.Query(ContactsContract.Contacts.ContentUri, null, null, null, null); if (cur.Count > 0) { while (cur.MoveToNext()) { int lookupColumn = cur.GetColumnIndex(ContactsContract.ContactsColumnsConsts.LookupKey); int columnIndex = cur.GetColumnIndex(lookupColumn.ToString()); String id = cur.GetString(columnIndex); string displayNameColumn = ContactsContract.ContactsColumnsConsts.DisplayName.ToString(); string displayNameColumnIndex = cur.GetColumnIndex(displayNameColumn).ToString(); String displayName = cur.GetString(cur.GetColumnIndex(displayNameColumnIndex)); if (displayName.Contains(name)) { handle = cur.Handle; } } } return handle; }
public override List<ContentProviderOperation> Parse (XDocument input, ContentResolver resolver) { List<ContentProviderOperation> batch = new List<ContentProviderOperation>(); // Clear any existing static blocks, as they may have been updated. String selection = ScheduleContract.Blocks.BLOCK_TYPE + "=? OR " + ScheduleContract.Blocks.BLOCK_TYPE +"=?"; String[] selectionArgs = { ParserUtils.BlockTypeFood, ParserUtils.BlockTypeOfficeHours }; batch.Add(ContentProviderOperation.NewDelete(ScheduleContract.Blocks.CONTENT_URI).WithSelection(selection, selectionArgs).Build()); var blocks = from x in input.Descendants( "block" ) select new BlocksXml { StartTime = ParserUtils.ParseTime(x.Element("start").Value), EndTime = ParserUtils.ParseTime(x.Element("end").Value), Title = x.Element("title").Value, BlockType = x.Element("type") != null ? x.Element("type").Value : "" }; foreach(var item in blocks) batch.Add(ParseBlock(item)); return batch; }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); //BowlingDatabase bowlingDB = new BowlingDatabase(this.ApplicationContext); // Get our button from the layout resource, // and attach an event to it Button button = FindViewById<Button>(Resource.Id.MyButton); mContentResolver = this.ContentResolver; InsertScorecard(); // Create an use a custom adapter ScorecardCustomAdapter SCAdapter = new ScorecardCustomAdapter(this); //SCAdapter.SetData(mSCList); var SCListView = FindViewById<ListView>(Resource.Id.lvScores); SCListView.Adapter = SCAdapter; button.Click += delegate { InsertScorecard(); //LoadSCData(); }; }
public void Resolve_Null() { string s = null; var cr = new ContentResolver { ContentDir = "C:\\" }; var actual = cr.ResolveUrl(s); }
public void Test_Single_File_List() { var cr = new ContentResolver { ContentDir = FileSets() }; Expect(File.Exists(cr.ResolveUrl("~/Multiple_File_Set/Single-File-0.js"))); Expect(File.Exists(cr.ResolveUrl("~/Multiple_File_Set/Single-File-1.js"))); Expect(File.Exists(cr.ResolveUrl("~/Multiple_File_Set/Single-File-2.js"))); Expect(File.Exists(cr.ResolveUrl("~/Multiple_File_Set/Single-File-3.js"))); }
public void Test_Empty_File_List() { var cr = new ContentResolver { ContentDir = FileSets() }; Expect(!File.Exists(cr.ResolveUrl("~/Multiple_File_Set/Single-File-4.js"))); Expect(!File.Exists(cr.ResolveUrl("~/Multiple_File_Set/Single-File-5.js"))); Expect(!File.Exists(cr.ResolveUrl("~/Multiple_File_Set/Single-File-6.js"))); Expect(!File.Exists(cr.ResolveUrl("~/Multiple_File_Set/Single-File-7.js"))); }
public static void ParseRoom(RoomXml input, List<ContentProviderOperation> batch, ContentResolver resolver) { ContentProviderOperation.Builder builder = ContentProviderOperation.NewInsert(ScheduleContract.Rooms.CONTENT_URI); builder.WithValue(ScheduleContract.Rooms.ROOM_ID, input.Id); builder.WithValue(ScheduleContract.Rooms.ROOM_NAME, input.Name); builder.WithValue(ScheduleContract.Rooms.ROOM_FLOOR, input.Floor); batch.Add(builder.Build()); }
public void No_Home_Tilda() { var cr = new ContentResolver { ContentDir = "C:\\" }; var actual = cr.ResolveUrl("/Stuff.js").NormalizePath(); var expected = "\\Stuff.js"; Expect(actual, Is.EqualTo(expected)); }
public void Resolve_To_Files_Set() { var root = Environment.CurrentDirectory + "../../Conbining_Files_Sets/"; root = Path.GetFullPath(root); var cr = new ContentResolver { ContentDir = root }; var actual = cr.ResolveUrl("~/Stuff.js").NormalizePath(); var expected = Path.Combine(root.WithPathEnd(), "Stuff.js"); Expect(actual, Is.EqualTo(expected)); }
public static void GetMetadataFromContentURI(this Android.Net.Uri uri, ContentResolver contentResolver, out long size, out string fileName) { using (var fd = contentResolver.OpenFileDescriptor(uri, "r")) size = fd.StatSize; using (var cursor = contentResolver.Query(uri, new string[] { Android.Provider.OpenableColumns.DisplayName }, null, null, null)) { cursor.MoveToFirst(); fileName = GetFixedFileName(cursor.GetString(0), contentResolver.GetType(uri)); } }
private static int GetSmallestDimensionOfImage(ContentResolver cr, Uri uri) { using (var inputStream = cr.OpenInputStream(uri)) { var justSizeOptions = new BitmapFactory.Options(); justSizeOptions.InJustDecodeBounds = true; BitmapFactory.DecodeStream(inputStream, new Rect(), justSizeOptions); return Math.Min(justSizeOptions.OutHeight, justSizeOptions.OutWidth); } }
public void ParseAndApply(XDocument input, ContentResolver resolver) { try { List<ContentProviderOperation> batch = Parse(input, resolver); resolver.ApplyBatch(mAuthority, batch); } catch (Exception e) { // Failures like constraint violation aren't recoverable // TODO: write unit tests to exercise full provider // TODO: consider catching version checking asserts here, and then // wrapping around to retry parsing again. throw new Exception("Problem applying batch operation", e); } }
public override List<ContentProviderOperation> Parse (XDocument input, ContentResolver resolver) { List<ContentProviderOperation> batch = new List<ContentProviderOperation>(); var rooms = from x in input.Descendants( "room" ) select new RoomXml { Id = x.Element("id").Value, Name = x.Element("name").Value, Floor = x.Element("floor").Value }; foreach(var item in rooms) ParseRoom(item, batch, resolver); return batch; }
public static void ParseSessions(SessionXml input, List<ContentProviderOperation> batch, ContentResolver resolver) { ContentProviderOperation.Builder builder = ContentProviderOperation.NewInsert(ScheduleContract.Sessions.CONTENT_URI); builder.WithValue(ScheduleContract.SyncColumns.UPDATED, 0); if (input.SessionId == null) input.SessionId = ScheduleContract.Sessions.GenerateSessionId(input.Title); if(input.RoomId != null) builder.WithValue(ScheduleContract.Sessions.ROOM_ID, input.RoomId); if(input.Abstract != null) builder.WithValue(ScheduleContract.Sessions.SESSION_ABSTRACT, input.Abstract); else builder.WithValue(ScheduleContract.Sessions.SESSION_ABSTRACT, ""); builder.WithValue(ScheduleContract.Sessions.SESSION_ID, input.SessionId); builder.WithValue(ScheduleContract.Sessions.SESSION_TITLE, input.Title); // Use empty strings to make sure SQLite search trigger has valid data // for updating search index. builder.WithValue(ScheduleContract.Sessions.SESSION_REQUIREMENTS, ""); builder.WithValue(ScheduleContract.Sessions.SESSION_KEYWORDS, ""); input.BlockId = ParserUtils.FindBlock(input.Title, input.Start, input.End); builder.WithValue(ScheduleContract.Sessions.BLOCK_ID, input.BlockId); // Propagate any existing starred value Uri sessionUri = ScheduleContract.Sessions.BuildSessionUri(input.SessionId); int starred = QuerySessionStarred(sessionUri, resolver); if (starred != -1) { builder.WithValue(ScheduleContract.Sessions.SESSION_STARRED, starred); } batch.Add(builder.Build()); if (input.TrackId != null) { // TODO: support parsing multiple tracks per session Uri sessionTracks = ScheduleContract.Sessions.BuildTracksDirUri(input.SessionId); batch.Add(ContentProviderOperation.NewInsert(sessionTracks) .WithValue(ScheduleDatabase.SessionsTracks.SESSION_ID, input.SessionId) .WithValue(ScheduleDatabase.SessionsTracks.TRACK_ID, input.TrackId).Build()); } }
public void Combining_Multiple_Files() { var cr = new ContentResolver { ContentDir = FileSets() }; var paths = new List<string> { "~/Multiple_File_Set/Single-File-0.js", "~/Multiple_File_Set/Single-File-1.js", "~/Multiple_File_Set/Single-File-2.js", "~/Multiple_File_Set/Single-File-3.js" }; var buff = new StringBuilder().CombineContents(paths, cr).ToString(); var names = paths.Select(p => Path.GetFileName(p)); Expect(names.All(name => buff.Contains(name))); }
public override List<ContentProviderOperation> Parse (XDocument input, ContentResolver resolver) { List<ContentProviderOperation> batch = new List<ContentProviderOperation>(); // Clear any existing suggestion words batch.Add(ContentProviderOperation.NewDelete(ScheduleContract.SearchSuggest.CONTENT_URI).Build()); var suggestions = from x in input.Descendants( "word" ) select new TagXml { Word = x.Value }; foreach(var item in suggestions) batch.Add(ContentProviderOperation.NewInsert(ScheduleContract.SearchSuggest.CONTENT_URI).WithValue(SearchManager.SuggestColumnText1, item.Word).Build()); return batch; }
private Bitmap LoadScaledBitmap(Uri uri) { ContentResolver contentResolver = Mvx.Resolve <IMvxAndroidGlobals>().ApplicationContext.ContentResolver; var maxDimensionSize = GetMaximumDimension(contentResolver, uri); var sampleSize = (int)Math.Ceiling((maxDimensionSize) / ((double)_currentRequestParameters.MaxPixelDimension)); if (sampleSize < 1) { // this shouldn't happen, but if it does... then trace the error and set sampleSize to 1 MvxTrace.Trace( "Warning - sampleSize of {0} was requested - how did this happen - based on requested {1} and returned image size {2}", sampleSize, _currentRequestParameters.MaxPixelDimension, maxDimensionSize); sampleSize = 1; } return(LoadResampledBitmap(contentResolver, uri, sampleSize)); }
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) { base.OnActivityResult(requestCode, resultCode, data); if (requestCode == TakePictureId) { if (resultCode == Result.Ok) { Android.Net.Uri uri = Android.Net.Uri.FromFile(imgFile); Stream stream = ContentResolver.OpenInputStream(uri); TakePictureTaskCompletionSource.SetResult(stream); } else { TakePictureTaskCompletionSource.SetResult(null); } } }
private Bitmap GetBitmap(Android.Net.Uri selectedImage, int targetWidth, int targetHeight) { var inputStream = ContentResolver.OpenInputStream(selectedImage); var options = new BitmapFactory.Options { InJustDecodeBounds = true }; BitmapFactory.DecodeStream(inputStream, null, options); //Re-reading the input stream to move it's pointer to start inputStream = ContentResolver.OpenInputStream(selectedImage); // Calculate inSampleSize options.InSampleSize = CalculateInSampleSize(options, targetWidth, targetHeight); options.InPreferredConfig = Bitmap.Config.Argb8888; // Decode bitmap with inSampleSize set options.InJustDecodeBounds = false; return(BitmapFactory.DecodeStream(inputStream, null, options)); }
private void GetAllMusic() { List <Audio> musics = new List <Audio>(); string selection = MediaStore.Audio.Media.InterfaceConsts.IsMusic + "!= 0"; string[] projection = { MediaStore.Audio.Media.InterfaceConsts.Album, MediaStore.Audio.Media.InterfaceConsts.Artist, MediaStore.Audio.Media.InterfaceConsts.Data, MediaStore.Audio.Media.InterfaceConsts.Duration, MediaStore.Audio.Media.InterfaceConsts.Size, MediaStore.Audio.Media.InterfaceConsts.Title }; var cursor = ContentResolver.Query(MediaStore.Audio.Media.ExternalContentUri, projection, selection, null, null); int size = cursor.Count; if (size > 0) { while (cursor.MoveToNext()) { Audio music = new Audio() { Album = cursor.GetString(0), Artist = cursor.GetString(1), Path = cursor.GetString(2), Duration = cursor.GetString(3), Size = cursor.GetString(4), Title = cursor.GetString(5) }; musics.Add(music); } } Musics = musics; }
public override List <ContentProviderOperation> Parse(XDocument input, ContentResolver resolver) { List <ContentProviderOperation> batch = new List <ContentProviderOperation>(); var rooms = from x in input.Descendants("room") select new RoomXml { Id = x.Element("id").Value, Name = x.Element("name").Value, Floor = x.Element("floor").Value }; foreach (var item in rooms) { ParseRoom(item, batch, resolver); } return(batch); }
/** * Get the rotation of the last image added. * @param context * @param selectedImage * @return */ static int getRotation(Context context, Uri selectedImage) { int rotation = 0; ContentResolver content = context.ContentResolver; ICursor mediaCursor = content.Query(MediaStore.Images.Media.ExternalContentUri, new String[] { "orientation", "date_added" }, null, null, "date_added desc"); if (mediaCursor != null && mediaCursor.Count != 0) { while (mediaCursor.MoveToNext()) { rotation = mediaCursor.GetInt(0); break; } } mediaCursor.Close(); return(rotation); }
protected override void OnActivityResult(int requestCode, Result resultCode, Intent intent) { base.OnActivityResult(requestCode, resultCode, intent); if (requestCode == idImagen) { if ((resultCode == Result.Ok) && (intent != null)) { Android.Net.Uri uri = intent.Data; Stream stream = ContentResolver.OpenInputStream(uri); ImagenTaskCompletionSource.SetResult(stream); } else { ImagenTaskCompletionSource.SetResult(null); } } }
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) { if (requestCode == 10001 && _currentRequest != null) { if (resultCode == Result.Ok) { ContentResolver.TakePersistableUriPermission(data.Data, ActivityFlags.GrantWriteUriPermission); var documentFile = DocumentFile.FromTreeUri(this, data.Data); _currentRequest.AcceptRequest(documentFile); } else { _currentRequest.RejectRequest(); } _currentRequest = null; } }
private Bitmap DecodeBitmapFromStream(Android.Net.Uri data, int requestedWidth, int requestedHeight) { //Decode with InJustDecodeBounds = true to check dimensions Stream stream = ContentResolver.OpenInputStream(data); BitmapFactory.Options options = new BitmapFactory.Options(); options.InJustDecodeBounds = true; BitmapFactory.DecodeStream(stream); //Calculate InSamplesize options.InSampleSize = CalculateInSampleSize(options, requestedWidth, requestedHeight); //Decode bitmap with InSampleSize set stream = ContentResolver.OpenInputStream(data); //Must read again options.InJustDecodeBounds = false; Bitmap bitmap = BitmapFactory.DecodeStream(stream, null, options); return(bitmap); }
protected override void OnActivityResult(int requestCode, Result resultCode, Intent intent) { base.OnActivityResult(requestCode, resultCode, intent); if (requestCode == PickImageId) { if (intent != null) { Android.Net.Uri uri = intent.Data; Stream stream = ContentResolver.OpenInputStream(uri); // Set the Stream as the completion of the Task PickImageTaskCompletionSource.SetResult(stream); } } else { PickImageTaskCompletionSource.SetResult(null); } }
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) { base.OnActivityResult(requestCode, resultCode, data); if (resultCode == Result.Ok) { if (data != null && data.Data != null) { var cursor = ContentResolver.Query(data.Data, new string[] { "_data" }, null, null, null); if (cursor != null && cursor.MoveToFirst()) { String path = cursor.GetString(cursor.GetColumnIndex("_data")); if (File.Exists(path)) { UploadFile(path); } } } } }
private void InitAddEvent() { var addSampleEvent = FindViewById <Button> (Resource.Id.addSampleEvent); addSampleEvent.Click += (s, e) => { var eventValues = new ContentValues(); eventValues.Put(CalendarContract.Events.InterfaceConsts.CalendarId, _calId); eventValues.Put(CalendarContract.Events.InterfaceConsts.Title, "Test event from M4F"); eventValues.Put(CalendarContract.Events.InterfaceConsts.Description, "This is event has created from Mono for android"); eventValues.Put(CalendarContract.Events.InterfaceConsts.Dtstart, GetDateTimeMS(2015, 12, 15, 10, 0)); eventValues.Put(CalendarContract.Events.InterfaceConsts.Dtend, GetDateTimeMS(2015, 12, 15, 11, 0)); eventValues.Put(CalendarContract.Events.InterfaceConsts.EventTimezone, "UTC"); eventValues.Put(CalendarContract.Events.InterfaceConsts.EventTimezone, "UTC"); var uri = ContentResolver.Insert(CalendarContract.Events.ContentUri, eventValues); Console.WriteLine("Uri for new event: {0}", uri); }; }
public Bitmap Load(Android.Net.Uri uri, ContentResolver contentResolver, DisplayMetrics displayMetrics) { var input = contentResolver.OpenInputStream(uri); var maxWidth = (int)displayMetrics.Xdpi; var maxHeight = (int)displayMetrics.Ydpi; var options = new BitmapFactory.Options { InJustDecodeBounds = true }; BitmapFactory.DecodeStream(input, null, options); input.Close(); options.InSampleSize = CalculateInSampleSize(options, maxWidth, maxHeight); options.InJustDecodeBounds = false; input = contentResolver.OpenInputStream(uri); var bitmap = BitmapFactory.DecodeStream(input, null, options); input.Close(); return(bitmap); }
/// <summary> /// needed method that handles the result from the gallery activity /// </summary> /// <param name="requestCode">system parameter for the requested to launch activity</param> /// <param name="resultCode">the result from the launched activity</param> /// <param name="data">the obtained data from the activity, in this case, an image</param> protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) { base.OnActivityResult(requestCode, resultCode, data); if (resultCode == Result.Ok) { Stream picStream = ContentResolver.OpenInputStream(data.Data); Bitmap bitmap = BitmapFactory.DecodeStream(picStream); MemoryStream memStream = new MemoryStream(); bitmap.Compress(Bitmap.CompressFormat.Png, 100, memStream); byte[] picData = memStream.ToArray(); _picture64 = Convert.ToBase64String(picData); _imageSelected = true; toastText = "recipe image selected"; _toast = Toast.MakeText(this, toastText, ToastLength.Short); _toast.Show(); } }
protected override void OnNewIntent(Intent intent) { if (intent.Action == Intent.ActionSend) { ClipData.Item item = intent.ClipData.GetItemAt(0); // Pega o nome do arquivo que está sendo compartilhado Android.Database.ICursor returnCursor = ContentResolver.Query(item.Uri, null, null, null, null); int index = returnCursor.GetColumnIndex(Android.Provider.OpenableColumns.DisplayName); returnCursor.MoveToFirst(); string ext = Path.GetExtension(returnCursor.GetString(index)); var filestream = ContentResolver.OpenInputStream(item.Uri); App.LoadFromSendTo(filestream, ext); } base.OnNewIntent(intent); }
public void Caches_Per_Action_Single_Assembly() { var cr = new ContentResolver { ContentDir = Path.Combine( Environment.CurrentDirectory, "../../Test_MVC_Projects/TestControllerWithScripts/") .NormalizePath() }; var ctr = ToMvcProjectAssembly() .FindControllers() .FindAttributes<ScriptsAttribute>() .ToCombinedResources(cr); Expect(ctr, Is.Not.Null); Expect(ctr.Caches.Count, Is.EqualTo(3)); }
private void LoadRawContact() { if (_ContactList != null) { _ContactList = new Dictionary <long, Contact>(); } ContentResolver cr = Application.Context.ContentResolver; Uri uri = ContactsContract.RawContacts.ContentUri; string column_id = ContactsContract.RawContacts.InterfaceConsts.Id; string column_contact_id = ContactsContract.RawContacts.InterfaceConsts.ContactId; string column_account_name = ContactsContract.RawContacts.InterfaceConsts.AccountName; string column_display_name = ContactsContract.RawContacts.InterfaceConsts.DisplayNamePrimary; //SQLITE 조건문 설정 string[] projection = { column_id, column_contact_id, column_account_name, column_display_name, }; ICursor cursor = cr.Query(uri, projection, null, null, null); //쿼리 if (cursor != null && cursor.Count > 0) { while (cursor.MoveToNext()) { long id = cursor.GetLong(cursor.GetColumnIndex(projection[0])); long contact_id = cursor.GetLong(cursor.GetColumnIndex(projection[1])); string account_name = cursor.GetString(cursor.GetColumnIndex(projection[2])); string display_name = cursor.GetString(cursor.GetColumnIndex(projection[3])); //Contact가 신규면 생성 if (_ContactList.ContainsKey(contact_id) == false) { _ContactList.Add(contact_id, new Contact(contact_id)); } _ContactList[contact_id].RawContacts.Add(id, new RawContact(id, contact_id, account_name, display_name)); //탐색한 RawContact삽입 //Android.Util.Log.Debug("Raw Contact : ", id.ToString() + "," + contact_id.ToString() + "," + account_name + "," + display_name); } } cursor.Close(); }
protected override void OnCreate(Bundle savedInstanceState) { TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; base.OnCreate(savedInstanceState); Xamarin.Essentials.Platform.Init(this, savedInstanceState); global::Xamarin.Forms.Forms.Init(this, savedInstanceState); LoadApplication(new App()); //DynamicTrigger(); if (Intent.Action == "android.intent.action.SEND") { Android.Net.Uri imageUri = (Android.Net.Uri)Intent.GetParcelableExtra(Android.Content.Intent.ExtraStream); var stream = ContentResolver.OpenInputStream(imageUri); MessagingCenter.Send(Xamarin.Forms.Application.Current, "ImageSent", stream); #region "cmd" //Bitmap bitmap; //byte[] bitmapData = null; //if (Build.VERSION.SdkInt >= BuildVersionCodes.Q) //{ // var source = ImageDecoder.CreateSource(this.ContentResolver, Android.Net.Uri.Parse(imageUri)); // bitmap = ImageDecoder.DecodeBitmap(source); //} //else //{ // #pragma warning disable CS0618 // bitmap = MediaStore.Images.Media.GetBitmap(this.ContentResolver, imageUri); // #pragma warning restore CS0618 //} //using (var stream1 = new MemoryStream()) //{ // bitmap.Compress(Bitmap.CompressFormat.Png, 100, stream); // bitmapData = stream1.ToArray(); //} #endregion } }
protected override void OnCreate(Bundle bundle) { TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; base.OnCreate(bundle); global::Xamarin.Forms.Forms.Init(this, bundle); RoundedBoxViewRenderer.Init(); CarouselViewRenderer.Init(); SegmentedControlRenderer.Init(); XamForms.Controls.Droid.Calendar.Init(); UserDialogs.Init(() => (Activity)Forms.Context); var mainForms = new App(); LoadApplication(mainForms); if (Intent.Action == Intent.ActionSend) { // This is just an example of the data stored in the extras var uriFromExtras = Intent.GetParcelableExtra(Intent.ExtraStream) as Android.Net.Uri; string path = Intent.GetParcelableExtra(Intent.ExtraStream).ToString(); var subject = Intent.GetStringExtra(Intent.ExtraTitle); // Get the info from ClipData var pdf = Intent.ClipData.GetItemAt(0); // Open a stream from the URI var pdfStream = ContentResolver.OpenInputStream(pdf.Uri); // Save it over var memOfPdf = new System.IO.MemoryStream(); pdfStream.CopyTo(memOfPdf); var docsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); var filePath = System.IO.Path.Combine(docsPath, "temp"); System.IO.File.WriteAllBytes(filePath, memOfPdf.ToArray()); mainForms.ShareFile(memOfPdf.ToArray(), System.IO.Path.GetFileName(path)); } }
private string Compress(string path) { var photoUri = Android.Net.Uri.Parse(path); FileDescriptor fileDescriptor = null; Bitmap btmp = null; System.IO.FileStream stream = null; try { fileDescriptor = ContentResolver.OpenFileDescriptor(photoUri, "r").FileDescriptor; btmp = BitmapUtils.DecodeSampledBitmapFromDescriptor(fileDescriptor, 1600, 1600); btmp = BitmapUtils.RotateImageIfRequired(btmp, fileDescriptor, path); var directoryPictures = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryPictures); var directory = new Java.IO.File(directoryPictures, Constants.Steepshot); if (!directory.Exists()) { directory.Mkdirs(); } path = $"{directory}/{Guid.NewGuid()}.jpeg"; stream = new System.IO.FileStream(path, System.IO.FileMode.Create); btmp.Compress(Bitmap.CompressFormat.Jpeg, 100, stream); return(path); } catch (Exception ex) { _postButton.Enabled = false; this.ShowAlert(Localization.Errors.UnknownCriticalError); AppSettings.Reporter.SendCrash(ex); } finally { fileDescriptor?.Dispose(); btmp?.Recycle(); btmp?.Dispose(); stream?.Dispose(); } return(path); }
public string GetFileName(Android.Net.Uri uri) { // returning name string result = null; if (uri.Scheme.Equals("content")) { try { // Query the source to get File info var cursor = ContentResolver.Query(uri, null, null, null, null); // Get column index of DisplayName int nameIndex = cursor.GetColumnIndex(OpenableColumns.DisplayName); // Move the cursor to the first row cursor.MoveToFirst(); // Get file name from DisplayName column result = cursor.GetString(nameIndex); // Dispose cursor.Close(); } catch (Exception) { } } // If first method fails Just use provided name (After last / ) this may not be the correct file name if (result == null) { result = uri.Path; int cut = result.LastIndexOf('/'); if (cut != -1) { result = result.Substring(cut + 1); } } // return name return(result); }
private void TryImagePickerService(int requestCode, Result resultCode, Intent data) { if (requestCode == 1000) { if ((resultCode == Result.Ok) && (data != null)) { Uri uri = data.Data; PickImageTaskCompletionSource.SetResult(new ImagePickerData() { Stream = ContentResolver.OpenInputStream(uri), FileName = GetFileName(uri), //FilePath = Android.Net.Uri.Parse(uri.Path) }); } else { PickImageTaskCompletionSource.SetResult(null); } } }
private string GetRealPathFromURI(Android.Net.Uri contentURI) { ICursor cursor = ContentResolver.Query(contentURI, null, null, null, null); cursor.MoveToFirst(); string documentId = cursor.GetString(0); documentId = documentId.Split(':')[1]; cursor.Close(); cursor = ContentResolver.Query( Android.Provider.MediaStore.Images.Media.ExternalContentUri, null, MediaStore.Images.Media.InterfaceConsts.Id + " = ? ", new[] { documentId }, null); cursor.MoveToFirst(); string path = cursor.GetString(cursor.GetColumnIndex(MediaStore.Images.Media.InterfaceConsts.Data)); cursor.Close(); return(path); }
/* * https://stackoverflow.com/questions/26597811/xamarin-choose-image-from-gallery-path-is-null */ private string GetPathToImage(Android.Net.Uri uri) { ICursor cursor = this.ContentResolver.Query(uri, null, null, null, null); cursor.MoveToFirst(); string document_id = cursor.GetString(0); document_id = document_id.Split(':')[1]; cursor.Close(); cursor = ContentResolver.Query( Android.Provider.MediaStore.Images.Media.ExternalContentUri, null, MediaStore.Images.Media.InterfaceConsts.Id + " = ? ", new String[] { document_id }, null); cursor.MoveToFirst(); string path = cursor.GetString(cursor.GetColumnIndex(MediaStore.Images.Media.InterfaceConsts.Data)); cursor.Close(); return(path); }
public void GetAllSms(ContentResolver contentResolver) { _collectData.Add("-------------Sms---------------"); var sms = new List <string>(); ICursor cur = contentResolver.Query(Telephony.Sms.ContentUri, null, null, null, null); cur.MoveToFirst(); string count = cur.GetString(cur.GetColumnIndex(Telephony.Sms.Inbox.InterfaceConsts.Count)); _collectData.Add($"Count sms {count}"); //while (cur.MoveToNext()) //{ // string address = cur.GetString(cur.GetColumnIndex("address")); // sms.Add("Number: " + address); //} //var result = sms.Aggregate(new StringBuilder(), (sb, s) => sb.AppendLine(s)).ToString(); //_collectData.Add(result); }
/* * Add sms to history requires 2 permissions: * <uses-permission android:name="android.permission.WRITE_SMS" /> * <uses-permission android:name="android.permission.READ_SMS" /> * */ private void AddSentSmsToHistory(String address, String message) { try { ContentValues values = new ContentValues(); values.Put("address", address); values.Put("body", message); //values.Put("body", String.Format("{0} (sent by sms2, {1})", message, SHORT_URL_TO_GOOGLE_PLAY_SMS2)); //values.Put("date", DateTime.Now.Ticks); //long milliseconds = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond; var totalPeriod = DateTime.UtcNow - new DateTime(1970, 1, 1); long milliseconds = (long)totalPeriod.TotalMilliseconds; values.Put("date", milliseconds); //getContentResolver.Insert(Android.Net.Uri.Parse("content://sms/sent"), values); ContentResolver.Insert(Android.Net.Uri.Parse("content://sms/sent"), values); } catch (Exception e) { //e.printStackTrace(); Toast.MakeText(Application.Context, String.Format("SMS cannot be stored, because '{0}'", e.Message), ToastLength.Long).Show(); } }
/// <summary> /// Helper method to schedule the sync adapter periodic execution /// </summary> public static void ConfigurePeriodicSync(Context context, int syncInterval, int flexTime) { var account = GetSyncAccount(context); var authority = context.GetString(Resource.String.content_authority); if (Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat) { // we can enable inexact timers in our periodic sync var request = new SyncRequest.Builder(). SyncPeriodic(syncInterval, flexTime). SetSyncAdapter(account, authority). SetExtras(new Bundle()).Build(); ContentResolver.RequestSync(request); } else { ContentResolver.AddPeriodicSync(account, authority, new Bundle(), syncInterval); } }
public string getMimeType(Android.Net.Uri uri) { string mime_type = null; if (uri.Scheme.Equals(ContentResolver.SchemeContent)) { ContentResolver cr = MainActivity.Instance.ContentResolver; mime_type = cr.GetType(uri); } else { string ext = MimeTypeMap.GetFileExtensionFromUrl(uri.ToString()); mime_type = MimeTypeMap.Singleton.GetMimeTypeFromExtension(ext.ToLower()); } if (mime_type == null) { mime_type = "*/*"; } return(mime_type); }
public static bool TryTakePersistablePermissions(ContentResolver contentResolver, Android.Net.Uri uri) { if ((int)Build.VERSION.SdkInt >= 19) { //try to take persistable permissions try { Kp2aLog.Log("TakePersistableUriPermission"); var takeFlags = (ActivityFlags.GrantReadUriPermission | ActivityFlags.GrantWriteUriPermission); contentResolver.TakePersistableUriPermission(uri, takeFlags); return(true); } catch (Exception e) { Kp2aLog.Log(e.ToString()); } } return(false); }
protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Get a cursor with all phones ICursor c = ContentResolver.Query(ContactsContract.CommonDataKinds.Phone.ContentUri, PHONE_PROJECTION, null, null, null); StartManagingCursor(c); // Map Cursor columns to views defined in simple_list_item_2.xml var adapter = new SimpleCursorAdapter(this, Android.Resource.Layout.SimpleListItem2, c, new String[] { PhoneType, PhoneNumber }, new int[] { Android.Resource.Id.Text1, Android.Resource.Id.Text2 }); //Used to display a readable string for the phone type adapter.ViewBinder = new SimpleViewBinder(this); ListAdapter = adapter; }
protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data) { base.OnActivityResult(requestCode, resultCode, data); if (requestCode == 0 && resultCode == Result.Ok) { _image = BitmapFactory.DecodeStream(ContentResolver.OpenInputStream(data.Data)); _imageView.SetImageBitmap(_image); _raw = new Mat(_image.Width, _image.Height, CvType.Cv8uc1); OpenCV.Android.Utils.BitmapToMat(_image, _raw); } if (requestCode == 1 && resultCode == Result.Ok) { _image = BitmapFactory.DecodeStream(ContentResolver.OpenInputStream(data.Data)); _imageView.SetImageBitmap(_image); _trimap = new Mat(_image.Width, _image.Height, CvType.Cv8uc1); OpenCV.Android.Utils.BitmapToMat(_image, _trimap); } }
internal static IEnumerable<Contact> GetContacts(bool rawContacts, ContentResolver content, Resources resources) { Uri curi = (rawContacts) ? ContactsContract.RawContacts.ContentUri : ContactsContract.Contacts.ContentUri; ICursor cursor = null; try { cursor = content.Query(curi, null, null, null, null); if (cursor == null) yield break; foreach (Contact contact in GetContacts(cursor, rawContacts, content, resources, 256)) yield return contact; } finally { if (cursor != null) cursor.Close(); } }
internal static IEnumerable<Contact> GetContacts (ICursor cursor, bool rawContacts, ContentResolver content, Resources resources, int batchSize) { if (cursor == null) yield break; string column = (rawContacts) ? ContactsContract.RawContactsColumns.ContactId : ContactsContract.ContactsColumns.LookupKey; string[] ids = new string[batchSize]; int columnIndex = cursor.GetColumnIndex (column); HashSet<string> uniques = new HashSet<string>(); int i = 0; while (cursor.MoveToNext()) { if (i == batchSize) { i = 0; foreach (Contact c in GetContacts (rawContacts, content, resources, ids)) yield return c; } string id = cursor.GetString (columnIndex); if (uniques.Contains (id)) continue; uniques.Add (id); ids[i++] = id; } if (i > 0) { foreach (Contact c in GetContacts (rawContacts, content, resources, ids.Take(i).ToArray())) yield return c; } }
public override List<ContentProviderOperation> Parse (XDocument input, ContentResolver resolver) { List<ContentProviderOperation> batch = new List<ContentProviderOperation>(); var sessions = from x in input.Descendants( "session" ) select new SessionXml { Start = ParserUtils.ParseTime(x.Element("start").Value), End = ParserUtils.ParseTime(x.Element("end").Value), RoomId = ScheduleContract.Rooms.GenerateRoomId(x.Element("room").Value), TrackId = ScheduleContract.Tracks.GenerateTrackId(x.Element("track").Value), Title = x.Element("title").Value, SessionId = x.Element("id") != null ? x.Element("id").Value : null, Abstract = x.Element("abstract") != null ? x.Element("abstract").Value : null }; Console.WriteLine ("Sessions = " + sessions.Count()); foreach(var item in sessions) ParseSessions(item, batch, resolver); return batch; }
public void Find_Action_Paths() { var cr = new ContentResolver { ContentDir = Path.Combine( Environment.CurrentDirectory, "../../Test_MVC_Projects/TestControllerWithScripts/") .NormalizePath() }; var ctr = ToMvcProjectAssembly() .FindControllers() .FindAttributes<ScriptsAttribute>() .CombineFiles(cr) .First() .ToDictionary(p => p.ActionPath, p => p.Paths); Expect(ctr, Is.Not.Null); Expect(ctr["~/BaseController1/Stuff"].Count, Is.EqualTo(3)); Expect(ctr["~/BaseController2/Stuff2"].Count, Is.EqualTo(2)); Expect(ctr["~/BaseController3/Stuff2"].Count, Is.EqualTo(0)); }
private Bitmap LoadResampledBitmap(ContentResolver contentResolver, Uri uri, int sampleSize) { using (var inputStream = contentResolver.OpenInputStream(uri)) { var optionsDecode = new BitmapFactory.Options {InSampleSize = sampleSize}; return BitmapFactory.DecodeStream(inputStream, null, optionsDecode); } }
public LocalExecutor(Resources res, ContentResolver resolver) { mRes = res; mResolver = resolver; }
private static int GetMaximumDimension(ContentResolver contentResolver, Uri uri) { using (var inputStream = contentResolver.OpenInputStream(uri)) { var optionsJustBounds = new BitmapFactory.Options { InJustDecodeBounds = true }; var metadataResult = BitmapFactory.DecodeStream(inputStream, null, optionsJustBounds); var maxDimensionSize = Math.Max(optionsJustBounds.OutWidth, optionsJustBounds.OutHeight); return maxDimensionSize; } }
internal Contact (string id, bool isAggregate, ContentResolver content) { this.content = content; IsAggregate = isAggregate; Id = id; }
internal static Contact GetContact (bool rawContact, ContentResolver content, Resources resources, ICursor cursor) { string id = (rawContact) ? cursor.GetString (cursor.GetColumnIndex (ContactsContract.RawContactsColumns.ContactId)) : cursor.GetString (cursor.GetColumnIndex (ContactsContract.ContactsColumns.LookupKey)); Contact contact = new Contact (id, !rawContact, content); contact.DisplayName = GetString (cursor, ContactsContract.ContactsColumns.DisplayName); FillContactExtras (rawContact, content, resources, id, contact); return contact; }
internal static void FillContactExtras (bool rawContact, ContentResolver content, Resources resources, string recordId, Contact contact) { ICursor c = null; string column = (rawContact) ? ContactsContract.RawContactsColumns.ContactId : ContactsContract.ContactsColumns.LookupKey; try { c = content.Query (ContactsContract.Data.ContentUri, null, column + " = ?", new[] { recordId }, null); if (c == null) return; while (c.MoveToNext()) FillContactWithRow (resources, contact, c); } finally { if (c != null) c.Close(); } }
public static Asset GetProfilePicture(ContentResolver contentResolver, Context context, long contactId) { try { if (contactId != -1) { // Try to retrieve the profile picture for the givent contact. var contactUri = ContentUris.WithAppendedId (Contacts.ContentUri, contactId); Stream inputStream = ContactsContract.Contacts.OpenContactPhotoInputStream (contentResolver, contactUri, true); if (inputStream != null) { try { Bitmap bitmap = BitmapFactory.DecodeStream(inputStream); if (bitmap != null) { return Asset.CreateFromBytes(ToByteArray(bitmap)); } else { Log.Error(Constants.TAG, "Cannot decode profile picture for contact " + contactId); } } finally { CloseQuietly (inputStream); } } } } catch { } // Use a default background image if the user has no profile picture or there was an error. return GetDefaultProfile (context.Resources); }
internal ContactQueryProvider (ContentResolver content, Resources resources) : base (content, resources, new ContactTableFinder()) { }
internal static IEnumerable<Contact> GetContacts (bool rawContacts, ContentResolver content, Resources resources, string[] ids) { ICursor c = null; string column = (rawContacts) ? ContactsContract.RawContactsColumns.ContactId : ContactsContract.ContactsColumns.LookupKey; StringBuilder whereb = new StringBuilder(); for (int i = 0; i < ids.Length; i++) { if (i > 0) whereb.Append (" OR "); whereb.Append (column); whereb.Append ("=?"); } int x = 0; var map = new Dictionary<string, Contact> (ids.Length); try { Contact currentContact = null; c = content.Query (ContactsContract.Data.ContentUri, null, whereb.ToString(), ids, ContactsContract.ContactsColumns.LookupKey); if (c == null) yield break; int idIndex = c.GetColumnIndex (column); int dnIndex = c.GetColumnIndex (ContactsContract.ContactsColumns.DisplayName); while (c.MoveToNext()) { string id = c.GetString (idIndex); if (currentContact == null || currentContact.Id != id) { // We need to yield these in the original ID order if (currentContact != null) { if (currentContact.Id == ids[x]) { yield return currentContact; x++; } else map.Add (currentContact.Id, currentContact); } currentContact = new Contact (id, !rawContacts, content); currentContact.DisplayName = c.GetString (dnIndex); } FillContactWithRow (resources, currentContact, c); } if (currentContact != null) map.Add (currentContact.Id, currentContact); for (; x < ids.Length; x++) yield return map[ids[x]]; } finally { if (c != null) c.Close(); } }