Cannot set permission for documents on Visual web part Sharepoint 2010 Foundation - visual-studio-2010

Good day! I have an event handler that, when you add a document to the library redirects the user to a web form with the parameters of the document. In the web form, it displays the current user in the form of Checkboxlist. The user selects the appropriate group, and he presses the Save button. Following are assigned permissions to the document according to the selected group. The problem is that the resolution of the document is not assigned according to selected groups. Here's the handler code:
using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
using System.Web;
using System.IO;
namespace SharePointProject3.EventReceiver2
{
/// <summary>
/// События элемента списка
/// </summary>
public class EventReceiver2 : SPItemEventReceiver
{
private HttpContext _context;
public EventReceiver2()
{
_context = HttpContext.Current;
}
public override void ItemAdding(SPItemEventProperties properties)
{
//Временно отключаем срабатывание обработчика
EventFiringEnabled = false;
//Получаем файл из HttpContext
HttpPostedFile file = _context.Request.Files[0];
Stream fileStream = file.InputStream;
byte[] fileByte = new byte[file.ContentLength];
fileStream.Read(fileByte, 0, file.ContentLength);
//Загружаем файл в библиотеку документов
SPFile fileUploded = properties.Web.Files.Add(properties.AfterUrl, fileByte);
//Включаем обработчик обратно
EventFiringEnabled = true;
//Отменяем добавление файла, которое делал пользователь
properties.Cancel = true;
properties.Status = SPEventReceiverStatus.CancelWithRedirectUrl;
//Деламе редирект
properties.RedirectUrl = properties.Web.Url + "/test_perm/default.aspx?ID=" + fileUploded.UniqueId;
}
}
}
And here's the code of the Web Part:
using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Text;
using Microsoft.SharePoint.Utilities;
namespace CustomGroupAssignment.VisualWebPart1
{
public partial class VisualWebPart1UserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
using (SPSite site = new SPSite("http://kviten:83/"))
{
using (SPWeb web = site.OpenWeb())
{
SPUser currentUser = web.CurrentUser;
SPDocumentLibrary docLib = (SPDocumentLibrary)web.Lists["Test_Doc_Lib"];
SPGroupCollection webGroups = currentUser.Groups;
CheckBoxList1.DataSource = webGroups;
CheckBoxList1.DataValueField = "ID";
CheckBoxList1.DataTextField = "Name";
CheckBoxList1.DataBind();
foreach (ListItem li in CheckBoxList1.Items)
{
li.Selected = true;
}
try
{
string itemID = Page.Request.Params["ID"];
SPDocumentLibrary doclib = (SPDocumentLibrary)web.GetList(SPUrlUtility.CombineUrl(web.Url, "/DocLib2/Forms/AllItems.aspx"));
SPListItem item = doclib.GetItemByUniqueId(new Guid(itemID));
}
catch (Exception ex)
{
//Выводим ошибку
}
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
using (SPSite site = new SPSite("http://kviten:83/"))
{
using (SPWeb web = site.OpenWeb())
{
SPUser currentUser = web.CurrentUser;
SPDocumentLibrary docLib = (SPDocumentLibrary)web.Lists["Test_Doc_Lib"];
try
{
string itemID = Page.Request.Params["ID"];
SPDocumentLibrary doclib = (SPDocumentLibrary)web.GetList(SPUrlUtility.CombineUrl(web.Url, "/Test_Doc_Lib/"));
SPListItem item = doclib.GetItemByUniqueId(new Guid(itemID));
//Break the role inheritance from List and remove any RoleAssignments
//item.BreakRoleInheritance(false);
//while (item.RoleAssignments.Count > 0)
//{
// item.RoleAssignments.Remove(0);
//}
if (!item.HasUniqueRoleAssignments)
{
item.ResetRoleInheritance();
item.Update();
item.BreakRoleInheritance(false);
item.Update();
}
foreach (ListItem li in CheckBoxList1.Items)
{
if (li.Selected) //Response.Write("- " + li.Text + "<br/>");
{
// Give permissions to a specific group
SPGroup group = web.Groups.GetByID(Convert.ToInt32(li.Value));
SPPrincipal principalGroup = group;
SPRoleAssignment roleassignment_group = new SPRoleAssignment(group);
SPRoleAssignment roleAssignment = item.RoleAssignments.GetAssignmentByPrincipal(principalGroup);
item.RoleAssignments.Add(roleAssignment);
item.Update();
}
}
}
catch (Exception ex)
{
//Выводим ошибку
}
Context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
Context.Response.Flush();
Context.Response.End();
}
}
}
protected void btnCancel_Click(object sender, EventArgs e)
{
Context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
Context.Response.Flush();
Context.Response.End();
}
}
}
I can not understand why I cannot assign permissions to the document! Help please!
If you use the / / Response.Write ("-" + li.Text + "<br/>"); which commented out, we can see that the checkboxes are not selected and not displayed. item.ResetRoleInheritance(); executed and permission assigned to only the current user with no groups. In what could be the reason?

The right solution for a web part:
using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Text;
using Microsoft.SharePoint.Utilities;
namespace CustomGroupAssignment.VisualWebPart1
{
public partial class VisualWebPart1UserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
using (SPSite site = new SPSite("http://kviten:83/"))
{
using (SPWeb web = site.OpenWeb())
{
SPUser currentUser = web.CurrentUser;
SPDocumentLibrary docLib = (SPDocumentLibrary)web.Lists["Test_Doc_Lib"];
SPGroupCollection webGroups = currentUser.Groups;
CheckBoxList1.DataSource = webGroups;
CheckBoxList1.DataValueField = "ID";
CheckBoxList1.DataTextField = "Name";
CheckBoxList1.DataBind();
foreach (ListItem li in CheckBoxList1.Items)
{
li.Selected = true;
}
try
{
string itemID = Page.Request.Params["ID"];
SPDocumentLibrary doclib = (SPDocumentLibrary)web.GetList(SPUrlUtility.CombineUrl(web.Url, "/DocLib2/Forms/AllItems.aspx"));
SPListItem item = doclib.GetItemByUniqueId(new Guid(itemID));
}
catch (Exception ex)
{
//Выводим ошибку
}
}
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
using (SPSite site = new SPSite("http://kviten:83/"))
{
using (SPWeb web = site.OpenWeb())
{
SPUser currentUser = web.CurrentUser;
SPDocumentLibrary docLib = (SPDocumentLibrary)web.Lists["Test_Doc_Lib"];
string itemID = Page.Request.Params["ID"];
SPDocumentLibrary doclib = (SPDocumentLibrary)web.GetList(SPUrlUtility.CombineUrl(web.Url, "/Test_Doc_Lib/"));
SPListItem item = doclib.GetItemByUniqueId(new Guid(itemID));
foreach (ListItem li in CheckBoxList1.Items)
{
if (li.Selected) //Response.Write("- " + li.Text + "<br/>");
{
if (!item.HasUniqueRoleAssignments)
{
item.ResetRoleInheritance();
item.Update();
}
item.BreakRoleInheritance(false);
item.Update();
SPGroup group = web.Groups.GetByID(Convert.ToInt32(li.Value));
SPPrincipal principalGroup = (SPPrincipal)group;
//SPRoleAssignment roleassignment_group = new SPRoleAssignment(principalGroup);
SPRoleAssignment roleAssignment = item.Web.RoleAssignments.GetAssignmentByPrincipal(principalGroup);
item.RoleAssignments.Add(roleAssignment);
item.Update();
// var roleAssignment = new SPRoleAssignment(principalGroup);
// item.RoleAssignments.Add(roleAssignment);
// item.Update();
}
}
Context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
Context.Response.Flush();
Context.Response.End();
}
}
}
protected void btnCancel_Click(object sender, EventArgs e)
{
Context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
Context.Response.Flush();
Context.Response.End();
}
}
}

Related

xamarin bluetooth receiving data does not work

i'm having a problem with receiving data from HC-05 bluetooth module. Sending data from mobile to module works fine, but i can't figure out how to receive data from module. I think there will be problem in with Thread which contains listener function.
Thank's for help
here's the code:
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Bluetooth;
using Microcharts;
using Entry = Microcharts.Entry;
using Microcharts.Droid;
using SkiaSharp;
using System.Linq;
using System.Collections.Generic;
namespace BLE
{
[Activity(Label = "BLE", MainLauncher = true)]
public class MainActivity : Activity
{
BluetoothConnection myConnection = new BluetoothConnection();
protected override void OnCreate(Bundle savedInstanceState)
{
var metrics = Resources.DisplayMetrics;
var width = metrics.WidthPixels;
var height = metrics.HeightPixels;
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
Button buttonConnect = FindViewById<Button>(Resource.Id.button1);
Button buttonDisconnect = FindViewById<Button>(Resource.Id.button2);
buttonConnect.LayoutParameters.Width = Convert.ToInt32(width * 0.5);
buttonDisconnect.LayoutParameters.Width = Convert.ToInt32(width * 0.5);
TextView connected = FindViewById<TextView>(Resource.Id.textView1);
BluetoothSocket _socket = null;
System.Threading.Thread listenThread = new System.Threading.Thread(listener);
listenThread.Abort();
buttonConnect.Click += delegate
{
try
{
buttonDisconnect.Enabled = false;
buttonConnect.Enabled = true;
listenThread.Abort();
myConnection.thisDevice.Dispose();
myConnection.thisSocket.OutputStream.WriteByte(187);
myConnection.thisSocket.OutputStream.Close();
myConnection.thisSocket.Close();
myConnection = new BluetoothConnection();
_socket = null;
connected.Text = "Disconnected!";
}
catch { }
listenThread.Start();
myConnection = new BluetoothConnection();
myConnection.thisSocket = null;
_socket = null;
myConnection.getAdapter();
myConnection.thisAdapter.StartDiscovery();
try
{
myConnection.getDevice();
myConnection.thisDevice.SetPairingConfirmation(false);
myConnection.thisDevice.Dispose();
myConnection.thisDevice.SetPairingConfirmation(true);
myConnection.thisDevice.CreateBond();
}
catch (Exception deviceEX)
{
}
myConnection.thisAdapter.CancelDiscovery();
_socket = myConnection.thisDevice.CreateRfcommSocketToServiceRecord(Java.Util.UUID.FromString("00001101-0000-1000-8000-00805f9b34fb"));
myConnection.thisSocket = _socket;
try
{
myConnection.thisSocket.Connect();
connected.Text = "Connected!";
buttonDisconnect.Enabled = true;
buttonConnect.Enabled = false;
if (listenThread.IsAlive == false)
{
listenThread.Start();
}
}
catch (Exception CloseEX)
{
}
};
buttonDisconnect.Click += delegate
{
try
{
buttonConnect.Enabled = true;
listenThread.Abort();
myConnection.thisDevice.Dispose();
myConnection.thisSocket.OutputStream.WriteByte(187);
myConnection.thisSocket.OutputStream.Close();
myConnection.thisSocket.Close();
myConnection = new BluetoothConnection();
_socket = null;
connected.Text = "Disconnected!";
}
catch { }
};
void listener()
{
TextView readTextView = FindViewById<TextView>(Resource.Id.textView2);
while (true)
{
try
{
byte[] buffer = new byte[1];
myConnection.thisSocket.InputStream.Read(buffer, 0, 1);
myConnection.thisSocket.InputStream.Close();
String dispString = System.Text.ASCIIEncoding.Default.GetString(buffer);
RunOnUiThread(() =>
{
//readTextView.Text = dispString;
System.Console.WriteLine(dispString);
});
}
catch (Java.IO.IOException)
{
RunOnUiThread(() =>
{
readTextView.Text = string.Empty;
});
break;
}
}
}
}
public class BluetoothConnection
{
public void getAdapter() { this.thisAdapter = BluetoothAdapter.DefaultAdapter; }
public void getDevice() { this.thisDevice = (from bd in this.thisAdapter.BondedDevices where bd.Name == "HC-05" select bd).FirstOrDefault(); }
public BluetoothAdapter thisAdapter { get; set; }
public BluetoothDevice thisDevice { get; set; }
public BluetoothSocket thisSocket { get; set; }
}
}
}
`
Thank's for help
I don't understand what this is used for in buttonConnect.Click event
try
{
buttonDisconnect.Enabled = false;
buttonConnect.Enabled = true;
listenThread.Abort();
myConnection.thisDevice.Dispose();
myConnection.thisSocket.OutputStream.WriteByte(187);
myConnection.thisSocket.OutputStream.Close();
myConnection.thisSocket.Close();
myConnection = new BluetoothConnection();
_socket = null;
connected.Text = "Disconnected!";
}
catch { }
and usually receive data like this(Simple usage):
System.Threading.Thread listenThread = new System.Threading.Thread(Listener);
buttonConnect.Click += delegate {
myConnection = new BluetoothConnection();
myConnection.getAdapter();
myConnection.getDevice();
_socket = myConnection.thisDevice.CreateRfcommSocketToServiceRecord(Java.Util.UUID.FromString("00001101-0000-1000-8000-00805f9b34fb"));
myConnection.thisSocket = _socket;
myConnection.thisSocket.Connect();
listenThread.Start();
}
private void Listener()
{
while (true)
{
try
{
byte[] buffer = new byte[1];
TextView readTextView = FindViewById<TextView>(Resource.Id.textView2);
myConnection.thisSocket.InputStream.Read(buffer, 0, 1);
myConnection.thisSocket.InputStream.Close();
String dispString = System.Text.ASCIIEncoding.Default.GetString(buffer);
RunOnUiThread(() =>
{
readTextView.Text = dispString;
System.Console.WriteLine(dispString);
});
}
catch (Java.IO.IOException)
{
TextView readTextView = FindViewById<TextView>(Resource.Id.textView2);
RunOnUiThread(() =>
{
readTextView.Text = string.Empty;
});
break;
}
}
}
}
public class BluetoothConnection
{
public void getAdapter() { this.thisAdapter = BluetoothAdapter.DefaultAdapter; }
public void getDevice() { this.thisDevice = (from bd in this.thisAdapter.BondedDevices where bd.Name == "hc-05" select bd).FirstOrDefault(); }
public BluetoothAdapter thisAdapter { get; set; }
public BluetoothDevice thisDevice { get; set; }
public BluetoothSocket thisSocket { get; set; }
}

using xam.Plugin.DownloadManager Xamarin forms

i am using xam.plugin.downloadmanager to download files in my app,once file download i wnats to redirect to downloads native page to view which i was download from server. is there any way ?? plesae help me
this is my code Anroid main activity class
using Android.OS;
using Plugin.DownloadManager;
using Plugin.DownloadManager.Abstractions;
using Xamarin.Forms.PlatformConfiguration;
using System.Linq;
using System.IO;
namespace Expertential.Droid
{
[Activity(Label = "Expertential", Icon = "#mipmap/icon", Theme = "#style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle bundle)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(bundle);
Downloaded();
global::Xamarin.Forms.Forms.Init(this, bundle);
Rg.Plugins.Popup.Popup.Init(this, bundle);
LoadApplication(new App());
}
public void Downloaded()
{
CrossDownloadManager.Current.PathNameForDownloadedFile = new System.Func<IDownloadFile, string>(file =>
{
string fileName = Android.Net.Uri.Parse(file.Url).Path.Split('/').Last();
return Path.Combine(ApplicationContext.GetExternalFilesDir(Android.OS.Environment.DirectoryDownloads).AbsolutePath, fileName);
});
}
}
}
viewmodel in here iam calling download .netstandard library
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Threading.Tasks;
using Expertential.Models;
using Expertential.Services;
using Expertential.ViewModels;
using Plugin.DownloadManager;
using Plugin.DownloadManager.Abstractions;
using Rg.Plugins.Popup.Services;
using Xamarin.Forms;
namespace Expertential.ViewModels
{
class CustomPopupViewModel :BaseViewModel
{
private CustomPopupViewModelService customPopupViewModelService;
private ObservableCollection<Attachments> attachment;
public ObservableCollection<Attachments> Attachment
{
get { return attachment; }
set
{
attachment = value;
RaisePropertyChanged(nameof(Attachment));
}
}
public CustomPopupViewModel()
{
}
private int _requertAttHeight;
public int requertAttHeight { get { return _requertAttHeight; }
set { _requertAttHeight = value;
RaisePropertyChanged(nameof(requertAttHeight));
}
}
private Boolean _taskLoader;
public Boolean taskLoader
{
get { return _taskLoader; }
set
{
_taskLoader = value;
RaisePropertyChanged(nameof(taskLoader));
}
}
public IDownloadFile File;
Boolean isDownloading = true;
#region custom function
public void GetAttachments(List<Attachments> attachment)
{
Attachment = new ObservableCollection<Attachments>();
if (attachment.Count > 0)
{
foreach (Attachments att in attachment)
{
var title = att.title;
string[] titleArray = title.Split('.');
if (titleArray.Length > 1)
{
setIconVisible(titleArray[1],att);
}
Attachment.Add(att);
}
requertAttHeight = 40 * attachment.Count;
}
}
public void setIconVisible(string content, Attachments att)
{
switch (content)
{
case "png":
case "jpg":
case "jpeg":
att.isWord = false;
att.isExcel = false;
att.isPdf = false;
att.isPpt = false;
att.isImage = true;
break;
case "ppt":
case "pptx":
att.isWord = false;
att.isExcel = false;
att.isPdf = false;
att.isPpt = true;
att.isImage = false;
break;
case "xlsx":
case "xls":
att.isWord = false;
att.isExcel = true;
att.isPdf = false;
att.isPpt = false;
att.isImage = false;
break;
case "docx":
att.isWord = true;
att.isExcel = false;
att.isPdf = false;
att.isPpt = false;
att.isImage = false;
break;
}
}
public async Task<string> GetFileFullUrl(string fileName)
{
var strValue = "";
customPopupViewModelService = new CustomPopupViewModelService();
strValue = await customPopupViewModelService.GetFileFullUrl(fileName);
return strValue;
}
public async void DownloadFile(string FileName)
{
Boolean target = false;
this.taskLoader = true;
var DownloadManager = CrossDownloadManager.Current;
var file = DownloadManager.CreateDownloadFile(FileName);
await Task.Yield();
await Task.Run(() =>
{
DownloadManager.Start(file, true);
while (isDownloading)
{
Task.Delay(100);
isDownloading = IsDownloading(file);
}
});
if (!isDownloading)
{
this.taskLoader = false;
target = await Application.Current.MainPage.DisplayAlert("Alert", "File Download Goto Download page to view", "Ok", "Cancel");
}
if (target)
{
// Device.OpenUri(new Uri("Downloads"));
try
{
await PopupNavigation.Instance.PopAsync();
// here i want to redirect to downloads app ->
// Intent myIntent = new Intent(Android.App.DownloadManager.ActionDownloadComplete);
}
catch (Exception e)
{
//// TODO: handle exception
//String data = e.getMessage();
}
// Environment.GetFolderPath(Environment.SpecialFolder.)
//var x = file.DestinationPathName;
//Device.OpenUri(new Uri(x));
}
}
public Boolean IsDownloading(IDownloadFile file)
{
if (file == null) return false;
switch (file.Status)
{
case DownloadFileStatus.INITIALIZED:
case DownloadFileStatus.PAUSED:
case DownloadFileStatus.PENDING:
case DownloadFileStatus.RUNNING:
return true;
case DownloadFileStatus.COMPLETED:
case DownloadFileStatus.CANCELED:
case DownloadFileStatus.FAILED:
return false;
default:
return false;
}
}
public void AbortDownloading()
{
CrossDownloadManager.Current.Abort(File);
}
#endregion
}
}
My understanding of your question tells me you want to open the default downloads application that Android has and it can be done as follows:
Intent intent = new Intent(DownloadManager.ActionViewDownloads);
intent.AddFlags(ActivityFlags.NewTask);
Android.App.Application.Context.StartActivity(intent);
Yes this is what i expected, i accomplished with some changes in your code
Intent intent = new Intent(DownloadManager.ActionViewDownloads);
intent.AddFlags(ActivityFlags.NewTask);
Android.App.Application.Context.StartActivity(intent);

Download and Save PDF for viewing

Im trying to download a PDF document from my app and display it in IBooks or at least make it available to read some how when its completed downloading.
I followed the download example from Xamarin which allows me download the PDF and save it locally. Its being save in the wrong encoding also.
This is what I've tried so far.
private void PdfClickHandler()
{
var webClient = new WebClient();
webClient.DownloadStringCompleted += (s, e) => {
var text = e.Result; // get the downloaded text
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string localFilename = $"{_blueways}.pdf";
// writes to local storage
File.WriteAllText(Path.Combine(documentsPath, localFilename), text);
InvokeOnMainThread(() => {
new UIAlertView("Done", "File downloaded and saved", null, "OK", null).Show();
});
};
var url = new Uri(_blueway.PDF);
webClient.Encoding = Encoding.UTF8;
webClient.DownloadStringAsync(url);
}
Do not use DownloadStringAsync for "binary" data, use DownloadDataAsync:
Downloads the resource as a Byte array from the URI specified as an asynchronous operation.
private void PdfClickHandler ()
{
var webClient = new WebClient ();
webClient.DownloadDataCompleted += (s, e) => {
var data = e.Result;
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string localFilename = $"{_blueways}.pdf";
File.WriteAllBytes (Path.Combine (documentsPath, localFilename), data);
InvokeOnMainThread (() => {
new UIAlertView ("Done", "File downloaded and saved", null, "OK", null).Show ();
});
};
var url = new Uri ("_blueway.PDF");
webClient.DownloadDataAsync (url);
}
// Retrieving the URL
var pdfUrl = new Uri("url.pdf"); //enter your PDF path here
// Open PDF URL with device browser to download
Device.OpenUri(pdfUrl);
//First Create Model Class FileDownload
public class FileDownload
{
public string FileUrl { get; set; }
public string FileName { get; set; }
}
//Create a view in xaml file for button on which we need to perform download functionality
<ImageButton BackgroundColor="Transparent" Clicked="DownloadFile_Clicked" x:Name="ImgFileReportDownload_ViewResult" IsVisible="False">
<ImageButton.Source>
<FontImageSource Glyph=""
Color="#1CBB8C"
Size="30"
FontFamily="{StaticResource FontAwesomeSolid}">
</FontImageSource>
</ImageButton.Source>
</ImageButton>
//Created a method in xaml.cs to download File on the click of button
private async void DownloadFile_Clicked(object sender, EventArgs e)
{
var status = await Permissions.CheckStatusAsync<Permissions.StorageWrite>();
if (status == PermissionStatus.Granted)
{
Uri uri = new Uri(fileReportNameViewResult);
string filename = System.IO.Path.GetFileName(uri.LocalPath);
FileDownload fileDownload = new FileDownload();
fileDownload.FileName = filename;
fileDownload.FileUrl = fileReportNameViewResult;
MessagingCenter.Send<FileDownload>(fileDownload, "Download");
}
else
{
status = await Permissions.RequestAsync<Permissions.StorageWrite>();
if (status != PermissionStatus.Granted)
{
await DisplayAlert("Permission Denied!", "\nPlease go to your app settings and enable permissions.", "Ok");
return;
}
}
}
//In MainActivity.cs , create a method
private void MessagingCenter()
{
Xamarin.Forms.MessagingCenter.Subscribe<FileDownload>(this, "Download", (s) =>
{
NotificationID += 4;
var intent = new Intent(this, typeof(Service.DownloadManager));
intent.PutExtra("url", s.FileUrl);
intent.PutExtra("name", s.FileName);
_layout.SetMinimumHeight(3000);
_layout.Bottom = 350; ;
Snackbar.Make(_layout, "Document is Downloading.", Snackbar.LengthShort)
.Show();
StartService(intent);
});
}
//Create a class DownloadManager.cs in Service folder , copy all the below code and paste , just change the Namespace
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace App.Droid.Service
{
[Service]
public class DownloadManager : Android.App.Service
{
AndroidNotificationManager NotificationManager = new AndroidNotificationManager();
public override IBinder OnBind(Intent intent)
{
return null;
}
public override void OnCreate()
{
}
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
Task.Run(() =>
{
int messageId = ++MainActivity.NotificationID;
string url = intent.GetStringExtra("url");
string filename = intent.GetStringExtra("name");
string extension = url.Substring(url.LastIndexOf('.'));
if (!filename.EndsWith(extension))
{
filename += extension;
}
NotificationManager.ScheduleNotification(filename, "", messageId);
String TempFileName = "";
try
{
HttpWebRequest Http = (HttpWebRequest)WebRequest.Create(url);
WebResponse Response = Http.GetResponse();
long length = Response.ContentLength;
var stream = Response.GetResponseStream();
string baseDir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads).AbsolutePath;
//string baseDir = Android.App.Application.Context.GetExternalFilesDir(Android.OS.Environment.DirectoryDownloads).AbsolutePath;
//string baseDir = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
//string baseDir = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
baseDir = Path.Combine(baseDir, filename.Substring(filename.LastIndexOf('/') + 1).Replace(' ', '_'));
Directory.CreateDirectory(baseDir);
//string filePath = Path.Combine(documentsPath, name);
if (filename.Length > 18)
{
TempFileName = filename.Substring(0, 18) + "...";
}
else
{
TempFileName = filename;
}
FileInfo fi = new FileInfo(Path.Combine(baseDir, filename.Substring(filename.LastIndexOf('/') + 1).Replace(' ', '_')));
var fis = fi.OpenWrite();
long count = 0;
int begpoint = 0;
bool iscancelled = false;
MessagingCenter.Subscribe<CancelNotificationModel>(this, "Cancel", sender =>
{
if (messageId == sender.ID)
{
iscancelled = true;
}
});
while (true)
{
try
{
if (iscancelled == true)
{
break;
}
// Read file
int bytesRead = 0;
byte[] b = new byte[1024 * 1024];
bytesRead = stream.Read(b, begpoint, b.Length);
if (bytesRead == 0)
break;
fis.Write(b, 0, bytesRead);
fis.Flush();
count += bytesRead;
System.Diagnostics.Debug.WriteLine(count + "-" + length);
if (count >= length)
break;
NotificationManager.ChangeProgress(TempFileName, (int)((count * 100) / length), messageId);
}
catch (Exception ex)
{
Http = (HttpWebRequest)WebRequest.Create(url);
WebHeaderCollection myWebHeaderCollection = Http.Headers;
Http.AddRange(count, length - 1);
Response = Http.GetResponse();
stream = Response.GetResponseStream();
}
}
fis.Close();
NotificationManager.RemoveNotification(messageId);
if (iscancelled == false)
{
new AndroidNotificationManager().DownloadCompleted(filename, "Download Completed", Path.Combine(baseDir, filename), ++messageId);
}
}
catch (Exception ex)
{
NotificationManager.RemoveNotification(messageId);
NotificationManager.FileCancelled(filename, "Download Cancelled, Please try again", ++messageId);
}
});
return StartCommandResult.NotSticky;
}
public override void OnDestroy()
{
}
}
public class CancelNotificationModel
{
public int ID { get; set; }
}
}
//Create a class AndroidNotificationManager.cs in Service folder
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using AndroidX.Core.App;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xamarin.Essentials;
using AndroidApp = Android.App.Application;
namespace App.Droid.Service
{
public class AndroidNotificationManager
{
const string channelId = "default";
const string channelName = "Default";
const string channelDescription = "The default channel for notifications.";
const int pendingIntentId = 0;
public const string TitleKey = "title";
public const string MessageKey = "message";
bool channelInitialized = false;
NotificationManager manager;
NotificationCompat.Builder builder;
public event EventHandler NotificationReceived;
public void Initialize()
{
CreateNotificationChannel();
}
public void RemoveNotification(int messageid)
{
manager.Cancel(messageid);
}
public int ScheduleNotification(string title, string message, int messageId, bool isInfinite = false)
{
if (!channelInitialized)
{
CreateNotificationChannel();
}
Intent intent = new Intent(AndroidApp.Context, typeof(MainActivity));
intent.PutExtra(TitleKey, title);
intent.PutExtra(MessageKey, message);
PendingIntent pendingIntent = PendingIntent.GetActivity(AndroidApp.Context, pendingIntentId, intent, PendingIntentFlags.OneShot);
builder = new NotificationCompat.Builder(AndroidApp.Context, channelId)
.SetContentTitle(title)
.SetContentText(message)
.SetPriority(NotificationCompat.PriorityLow)
.SetVibrate(new long[] { 0L })
.SetProgress(100, 0, isInfinite)
.SetSmallIcon(Resource.Drawable.checkcircle);
var notification = builder.Build();
manager.Notify(messageId, notification);
return messageId;
}
public void ChangeProgress(string filename, int progress, int messageId)
{
try
{
var actionIntent1 = new Intent();
actionIntent1.SetAction("Cancel");
actionIntent1.PutExtra("NotificationIdKey", messageId);
var pIntent1 = PendingIntent.GetBroadcast(Android.App.Application.Context, 0, actionIntent1, PendingIntentFlags.CancelCurrent);
var ProgressBuilder = new NotificationCompat.Builder(AndroidApp.Context, channelId)
.SetSmallIcon(Resource.Drawable.checkcircle)
.SetContentTitle(filename)
.SetVibrate(new long[] { 0L })
.AddAction(Resource.Drawable.checkcircle, "Cancel", pIntent1)
.SetPriority(NotificationCompat.PriorityLow)
.SetProgress(100, progress, false)
.SetContentText(progress + "%")
.SetAutoCancel(false);
System.Diagnostics.Debug.WriteLine(progress);
manager.Notify(messageId, ProgressBuilder.Build());
}
catch
{
}
}
public void DownloadCompleted(string filenametitle, string Message, string filepath, int messageId)
{
try
{
if (!channelInitialized)
{
CreateNotificationChannel();
}
var CompletedBuilder = new NotificationCompat.Builder(AndroidApp.Context, channelId)
.SetContentTitle(filenametitle)
.SetContentText(Message)
.SetAutoCancel(true)
.SetSmallIcon(Resource.Drawable.checkcircle);
Intent it = OpenFile(filepath, filenametitle);
if (it != null)
{
PendingIntent contentIntent =
PendingIntent.GetActivity(AndroidApp.Context,
pendingIntentId,
it,
PendingIntentFlags.OneShot
);
CompletedBuilder.SetContentIntent(contentIntent);
}
var notification = CompletedBuilder.Build();
manager.Notify(messageId, notification);
}
catch (Exception ex)
{
}
}
public void FileCancelled(string filenametitle, string Message, int messageId)
{
if (!channelInitialized)
{
CreateNotificationChannel();
}
var CompletedBuilder = new NotificationCompat.Builder(AndroidApp.Context, channelId)
.SetContentTitle(filenametitle)
.SetContentText(Message)
.SetAutoCancel(true)
.SetSmallIcon(Resource.Drawable.checkcircle)
.SetDefaults((int)NotificationDefaults.Sound | (int)NotificationDefaults.Vibrate);
var notification = CompletedBuilder.Build();
manager.Notify(messageId, notification);
}
public void ReceiveNotification(string title, string message)
{
}
void CreateNotificationChannel()
{
manager = (NotificationManager)AndroidApp.Context.GetSystemService(AndroidApp.NotificationService);
if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
{
var channelNameJava = new Java.Lang.String(channelName);
var channel = new NotificationChannel(channelId, channelNameJava, NotificationImportance.Low)
{
Description = channelDescription
};
manager.CreateNotificationChannel(channel);
}
channelInitialized = true;
}
public Intent OpenFile(string filePath, string fileName)
{
try
{
string application = "";
string extension = fileName.Substring(fileName.IndexOf('.'));
switch (extension.ToLower())
{
case ".doc":
case ".docx":
application = "application/msword";
break;
case ".pdf":
application = "application/pdf";
break;
case ".xls":
case ".xlsx":
application = "application/vnd.ms-excel";
break;
case ".jpg":
case ".jpeg":
case ".png":
application = "image/jpeg";
break;
case ".mp4":
application = "video/mp4";
break;
default:
application = "*/*";
break;
}
Java.IO.File file = new Java.IO.File(filePath);
bool isreadable =
file.SetReadable(true);
string ApplicationPackageName = AppInfo.PackageName;
var context = Android.App.Application.Context;
var component = new Android.Content.ComponentName(context, Java.Lang.Class.FromType(typeof(AndroidX.Core.Content.FileProvider)));
var info = context.PackageManager.GetProviderInfo(component, Android.Content.PM.PackageInfoFlags.MetaData);
var authority = info.Authority;
Android.Net.Uri uri = AndroidX.Core.Content.FileProvider.GetUriForFile(Android.App.Application.Context, authority, file);
Intent intent = new Intent(Intent.ActionView);
System.IO.File.AppendAllText((filePath + "backdebug.txt"), System.Environment.NewLine + "Point 3 uri done ");
intent.SetDataAndType(uri, application);
intent.AddFlags(ActivityFlags.GrantReadUriPermission);
intent.AddFlags(ActivityFlags.NoHistory);
intent.AddFlags(ActivityFlags.NewTask);
System.IO.File.AppendAllText((filePath + "backdebug.txt"), System.Environment.NewLine + "Point 4open file last ");
return intent;
}
catch (Exception ex)
{
Intent it = new Intent();
it.PutExtra("ex", ex.Message);
System.IO.File.AppendAllText((filePath + "backdebug.txt"), System.Environment.NewLine + "Point 4 uri done " + ex.Message);
return it;
}
}
}
}
Here is the sample code to download file in PCL Xamarin from remote server.
I have used PCLStorage library package which is available in Nuget. You just need download and install in your project.
public async void Downloadfile(string Url)
{
try
{
Uri url = new Uri(Url);
var client = new HttpClient();
IFolder rootfolder = FileSystem.Current.LocalStorage;
IFolder appfolder = await rootfolder.CreateFolderAsync("Download", CreationCollisionOption.OpenIfExists);
IFolder dbfolder = await appfolder.CreateFolderAsync("foldername", CreationCollisionOption.OpenIfExists);
IFile file = await dbfolder.CreateFileAsync(strReport_name, CreationCollisionOption.ReplaceExisting);
using (var fileHandler = await file.OpenAsync(PCLStorage.FileAccess.ReadAndWrite))
{
var httpResponse = await client.GetAsync(url);
byte[] dataBuffer = await httpResponse.Content.ReadAsByteArrayAsync();
await fileHandler.WriteAsync(dataBuffer, 0, dataBuffer.Length);
}
}
catch (Exception ex)
{
throw ex;
}
}

Show image from SQL Server 2008 in datagridview C#

I'm tired of searching for a solution. please help me.
I have a table with columns
p_id (int)
p_name (varchar50)
category (int)
price (money)
picture (Image)
Insertion process works perfectly, it is also showing me my database records.. but it sow me my filepath in gridview rather than show image...
Please help me... it is part of my project... and I don't know how to show retrieve image from database in Datagridview
I have done all my SQL connection work in Dall Class
Here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Image_task
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void insert_btn_Click(object sender, EventArgs e)
{
try
{
int count;
dall insert = new dall();
int id = Convert.ToInt32(id_txt.Text);
string name = name_txt.Text;
int cat = Convert.ToInt32(cat_txt.Text);
decimal price = Convert.ToDecimal(price_txt.Text);
string image=pic_txt.Text;
count = insert.insrt_up_del("insert into product values('" + id + "','" + name + "','" + cat + "','" + price + "','" + image + "')");
MessageBox.Show("Insert Successfully", "Successfull", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Form1_Load(object sender, EventArgs e)
{
insert_btn.Enabled=false;
}
private void browse_txt_Click(object sender, EventArgs e)
{
insert_btn.Enabled = true;
openFileDialog1.Filter = "Images (*.BMP;*.JPG;*.GIF,*.PNG,*.TIFF)|*.BMP;*.JPG;*.GIF;*.PNG;*.TIFF|" + "All files (*.*)|*.*";
if (openFileDialog1.ShowDialog()==DialogResult.OK)
{
pictureBox1.Image = new Bitmap(openFileDialog1.FileName);
pic_txt.Text = openFileDialog1.FileName;
}
}
private void search_btn_Click(object sender, EventArgs e)
{
dall select = new dall();
DataTable dt = new DataTable();
dt = select.select("Select * from product");
dataGridView1.DataSource = dt;
//DataGridViewImageColumn img = new DataGridViewImageColumn();
//img.DataPropertyName = "Picture";
//img.Width = 200;
//img.HeaderText = "Picture Column";
//img.ReadOnly = true;
//img.ImageLayout = DataGridViewImageCellLayout.Normal;
//dataGridView1.Columns.Add(img);
//dataGridView1.DataSource = new BindingSource(dt,null);
}
}
}
use data adapter
DataAdapter da = new DataAdapter("Select * from product",youconnection);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;

dynamically generated pageview issue

I have created dynamic tab function. When i create dynamic tab it will create pageview for that tab. But when i deleted that tab that pageview is not deleting. Can any one help me to fix this.
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Telerik.WebControls;
using Telerik;
public partial class Radstrip2 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Label PageContent;
protected System.Web.UI.WebControls.Repeater BuildingSummary;
protected Telerik.WebControls.PageView PageView1;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Tab tab = new Tab();
tab.Text = string.Format("New Page {0}", 1);
RadTabStrip1.Tabs.Add(tab);
PageView pageView = new PageView();
RadMultiPage1.PageViews.Add(pageView);
BuildPageViewContents(pageView, RadTabStrip1.Tabs.Count);
RadTabStrip1.SelectedIndex = 0;
}
}
private void BuildPageViewContents(PageView pageView, int index)
{
pageView.ID = "Page " + index.ToString();
pageView.Controls.Add(new LiteralControl(" <B>New page</B>" + (index).ToString()));
}
protected void Button1_Click(object sender, EventArgs e)
{
Tab tab = new Tab();
tab.Text = string.Format("New Page {0}", RadTabStrip1.Tabs.Count + 1);
RadTabStrip1.Tabs.Add(tab);
PageView pageView = new PageView();
pageView.ID = "Page " + pageView.Index.ToString();
RadMultiPage1.PageViews.Add(pageView);
BuildPageViewContents(pageView, RadTabStrip1.Tabs.Count);
RadTabStrip1.SelectedIndex = RadTabStrip1.SelectedIndex + 1;
RadMultiPage1.SelectedIndex = RadTabStrip1.SelectedIndex;
}
protected void Button2_Click(object sender, EventArgs e)
{
Tab currentTab = RadTabStrip1.InnerMostSelectedTab;
if (currentTab != null)
{
ITabContainer owner = currentTab.Owner;
owner.Tabs.Remove(currentTab);
//RadMultiPage1.PageViews.Remove(currentTab.PageView);
if (owner.Tabs.Count > 0)
{
owner.SelectedIndex = 0;
}
}
}
protected void RadMultiPage1_PageViewItemCreated1(PageView view, int viewIndex)
{
BuildPageViewContents(view, viewIndex + 1);
}
}
I see that in your Button2_Click() method you remove the currently selected tab but you don't remove the current page view. You can try with:
RadMultiPage1.PageViews.RemoveAt(RadMultiPage1.SelectedIndex);
This should remove the currently selected page view

Resources