display media library file size in custom module in Orchard - orchardcms

I have custom module for employee and i want to display cv document side on listing of employee in grid view.
how to get size of document? i have used media library to upload cv. can someone help me on it
thanks

Please follow the below code for get the file size.
Add Property in your ABCPart.cs( public string FileSize { get; set; })
After get list of record then add below code for get file size.
int cnt = 0;
foreach (var item in lstDocument)
{
var b = item.Fields.Single(f => f.Name == "YourMediaLibararyPickerFieldName");
if (item.Fields.Single(f => f.Name == "YourMediaLibararyPickerFieldName") != null)
{
var field = _contentManager.Get(((Orchard.MediaLibrary.Fields.MediaLibraryPickerField)item.Fields.Single(f => f.Name == "YourMediaLibararyPickerFieldName")).Ids[0]);
if (field != null && field.ContentType == "Document")
{
long a = ((Orchard.MediaLibrary.Models.DocumentPart)_contentManager.Get(((Orchard.MediaLibrary.Fields.MediaLibraryPickerField)item.Fields.Single(f => f.Name == "YourMediaLibararyPickerFieldName")).Ids[0]).As<Orchard.MediaLibrary.Models.DocumentPart>()).Length;
lstDocument[cnt].FileSize = (a / 1024).ToString() + " KB";
}
else
{
lstDocument[cnt].FileSize = "-";
}
}
else
{
lstDocument[cnt].FileSize = "-";
}
cnt++;
}

Related

Provide data lookup for PXSelector

I need advice either to convert the SQL to BQL or set the Resultset manipulated by C# code to the PXSelector.
I need to customize the AR Invoice and add 2 custom fields to record the COGS GL account and sub account for the inter company client when the inter company enter this invoice line as a bill. This custom field need to look up all sub accounts that is restricted to this Client's Branch ID and GL account. Basically all system's sub account lookup take care of the restriction group but for the custom fields; a custom PXSelector need to be written for this. Below is the SQL that supplies the require sub accounts but I need to know how to make the SQL query works in Acumatica
-- SQL for the required data
DECLARE #GLAccountCD nvarchar(10) = 'COGS'
DECLARE #BranchCD nvarchar(30) = 'PurchaseBranch'
SELECT *
FROM Sub
where (((CAST(Sub.groupmask as int) & CAST((SELECT GroupMask FROM Account WHERE AccountCD = #GLAccountCD AND CompanyID = 3 AND DeletedDatabaseRecord = 0) AS int)) > 1
AND (CAST(Sub.groupmask as int) & CAST((SELECT GroupMask FROM Branch WHERE BranchCD = #BranchCD AND CompanyID = 3 AND DeletedDatabaseRecord = 0) AS int)) > 1)
OR (Sub.GroupMask = 0 AND Sub.DeletedDatabaseRecord = 0))
AND CompanyID = 3
ORDER BY SubCD
--The below PXSelector provide all sub accounts regard of restriction group,
--I need the PXSelector to use the above SQL Query result
#region UsrAPBIllGLSubAccID
[PXDBInt]
[PXUIField(DisplayName="Bill COGS SubAccount")]
[PXSelector(typeof(Search<Sub.subID, Where<Sub.active, Equal<True>>, OrderBy<Desc<Sub.subCD>>>),
new Type[] {typeof(Sub.subCD),
typeof(Sub.description)},
SubstituteKey = typeof(Sub.subCD)
)]
public virtual int? UsrAPBIllGLSubAccID { get; set; }
public abstract class usrAPBIllGLSubAccID : IBqlField { }
#endregion
I think that would be achievable using the Match BQL clause.
GLAccess.cs file has BQL queries to restrict accounts based on Sub and Branch group mask using Match clause, this would be a good place to investigate:
public PXSelect<Sub> Sub;
protected virtual IEnumerable sub(
)
{
if (Group.Current != null && !String.IsNullOrEmpty(Group.Current.GroupName))
{
bool inserted = (Group.Cache.GetStatus(Group.Current) == PXEntryStatus.Inserted);
foreach (Sub item in PXSelect<Sub,
Where2<Match<Current<PX.SM.RelationGroup.groupName>>,
Or2<Match<Required<Sub.groupMask>>, Or<Sub.groupMask, IsNull>>>>
.Select(this, new byte[0]))
{
if (!inserted || item.Included == true)
{
Sub.Current = item;
yield return item;
}
else if (item.GroupMask != null)
{
PX.SM.RelationGroup group = Group.Current;
bool anyGroup = false;
for (int i = 0; i < item.GroupMask.Length && i < group.GroupMask.Length; i++)
{
if (group.GroupMask[i] != 0x00 && (item.GroupMask[i] & group.GroupMask[i]) == group.GroupMask[i])
{
Sub.Current = item;
yield return item;
}
anyGroup |= item.GroupMask[i] != 0x00;
}
if (!anyGroup)
{
Sub.Current = item;
yield return item;
}
}
}
}
else
{
yield break;
}
}
public PXSelect<Branch> Branch;
protected virtual IEnumerable branch(
)
{
if (Group.Current != null && !String.IsNullOrEmpty(Group.Current.GroupName))
{
bool inserted = (Group.Cache.GetStatus(Group.Current) == PXEntryStatus.Inserted);
foreach (Branch item in PXSelect<Branch,
Where2<Match<Current<PX.SM.RelationGroup.groupName>>,
Or<Match<Required<Branch.groupMask>>>>>
.Select(this, new byte[0]))
{
if (!inserted)
{
Branch.Current = item;
yield return item;
}
else if (item.GroupMask != null)
{
PX.SM.RelationGroup group = Group.Current;
bool anyGroup = false;
for (int i = 0; i < item.GroupMask.Length && i < group.GroupMask.Length; i++)
{
if (group.GroupMask[i] != 0x00 && (item.GroupMask[i] & group.GroupMask[i]) == group.GroupMask[i])
{
Branch.Current = item;
yield return item;
}
anyGroup |= item.GroupMask[i] != 0x00;
}
if (!anyGroup)
{
Branch.Current = item;
yield return item;
}
}
}
}
else
{
yield break;
}
}

Sharepoint: Value does not fall within the expected range

I am trying to import a logo of a web and its subsite in sharepoint 2013.
When I try to load the file for subsite then exception occur.
Value does not fall within the expected range
Here is my code
if (siteLogo != null)
{
File = web.GetFileByServerRelativeUrl(siteLogo);
Data = File.OpenBinaryStream();
customContext.Context.Load(File);
customContext.Context.ExecuteQuery();
}
First Time it works fine. But when it loads for subsite it generate exception.
I tried alot to solve this but unable to find the solution. Please help.
This is complete file
public Branding(SharePointClientContext customContext, string siteLogo, string alternateCss, ListItemCollection ltItemCollection, Microsoft.SharePoint.Client.Web web)
{
if (ltItemCollection != null)
{
ListItem item = ltItemCollection.Where(a => a.DisplayName == "Current").FirstOrDefault();
if (item.FieldValuesAsText != null && item.FieldValuesAsText.FieldValues["ThemeUrl"] != null && item.FieldValuesAsText.FieldValues["ThemeUrl"] != "")
{
string themeUrl = item.FieldValuesAsText.FieldValues["ThemeUrl"].Split(',')[1];
string themeFileName = themeUrl.Substring(themeUrl.LastIndexOf('/') + 1).ToLower();
ListItem selectedTheme = ltItemCollection.Where(a =>
a.FieldValuesAsText.FieldValues["ThemeUrl"].Split(',')[1].Substring(a.FieldValuesAsText.FieldValues["ThemeUrl"].Split(',')[1].LastIndexOf('/') + 1) == themeFileName
&& a.DisplayName != "Current").FirstOrDefault();
this.Theme = selectedTheme.DisplayName;
}
}
if (siteLogo != null)
{
File = web.GetFileByServerRelativeUrl(siteLogo);
Data = File.OpenBinaryStream();
customContext.Context.Load(File);
customContext.Context.ExecuteQuery();
File = null;
}
if (alternateCss != null && alternateCss != "")
{
CssFile = web.GetFileByServerRelativeUrl(web.SiteLogoUrl);
CssData = CssFile.OpenBinaryStream();
web.Context.Load(CssFile);
web.Context.ExecuteQuery();
CssFile = null;
}
}
And calling this in following way.
SharePointConstants.branding.Add(new Branding(customContext, siteLogo, AlternateCss, ltItemCollection, web));

Read Check Box, Radio Button Name and values from PDF using iText Sharp

I have a fillable PDF contains CheckBoxes and RadioButtons and TextBox.
How do i get the CheckBox Name and its value also how do we know that it is a checkbox / Radio Button?
i'm using iTextSharp and have look at my below code
PdfReader pdfReader = new PdfReader(FileName);
pdfReader.SelectPages("37");
MemoryStream oStream = new MemoryStream();
PdfStamper stamper = new PdfStamper(pdfReader, oStream);
AcroFields form = stamper.AcroFields;
if (form.Fields.Count() > 0)
{
IDictionary<string,AcroFields.Item> oDic= form.Fields;
foreach (string FieldName in oDic.Keys)
{
//FieldName - CheckBox name; i need to confirm that is a Checkbox...
}
foreach (AcroFields.Item oItem in oDic.Values)
{
// how do we get check box values
}
}
The following code may help you out, if you still need it. It only works for AcroForms
int BUTTON = 1;
int CHECK_BOX = 2;
int RADIO_BUTTON = 3;
int TEXT_FIELD = 4;
int LIST_BOX = 5;
int COMBO_BOX = 6;
PdfReader pdfReader = new PdfReader(path);
AcroFields af = pdfReader.AcroFields;
foreach (var field in af.Fields)
{
bool isRadio = RADIO_BUTTON == af.GetFieldType(field.Key));
}
Edit:
Also, field.Key is the name of the field and field.Value is the value at it.
For checkboxes, if(field.Value == "Yes") then it is selected... if it is anything else, it is not selected.
Edit:
And I just found how tro get Radio Button options, if you are needing them.
myKey k = new myKey(field.Key, af.GetField(field.Key), af.GetFieldType(field.Key));
if (k.isRadio())
{
try { k.options.AddRange(af.GetAppearanceStates(k.key)); }
catch { }
}
Keys.Add(k);
Radio buttons, checkbox and buttons are all actually the same type of field but with different flags set. You can see the flags in the PDF Spec section 12.7.4.2.1 Table 226.
int ffRadio = 1 << 15; //Per spec, 16th bit is radio button
int ffPushbutton = 1 << 16; //17th bit is push button
For a given Field you want to get the Widgets associated with it. Usually this is just one but can be more so you should account for this.
PdfDictionary w = f.Value.GetWidget(0);
Button fields will have their field type (/Ft) set to /Btn so check for that
if (!w.Contains(PdfName.FT) || !w.Get(PdfName.FT).Equals(PdfName.BTN)) {continue;/*Skipping non-buttons*/ }
For the current Widget get the optional field flags (/Ff) value or use zero if it doesn't exist.
int ff = (w.Contains(PdfName.FF) ? w.GetAsNumber(PdfName.FF).IntValue : 0);
Then just some simple math:
if ((ff & ffRadio) == ffRadio) {
//Is Radio
} else if (((ff & ffRadio) != ffRadio) && ((ff & ffPushbutton) != ffPushbutton)) {
//Is Checkbox
} else {
//Regular button
}
Below is a full-working C# WinForm 2011 app targeting iTextSharp 5.2.0 that shows off all of the above looking at a file called Test.pdf living on your desktop. Just add some logic to the conditionals to handle each button type.
using System;
using System.IO;
using System.Windows.Forms;
using iTextSharp.text.pdf;
namespace WindowsFormsApplication3 {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf");
PdfReader reader = new PdfReader(testFile);
var fields = reader.AcroFields;
int ffRadio = 1 << 15; //Per spec, 16th bit is radio button
int ffPushbutton = 1 << 16; //17th bit is push button
int ff;
//Loop through each field
foreach (var f in fields.Fields) {
//Get the widgets for the field (note, this could return more than 1, this should be checked)
PdfDictionary w = f.Value.GetWidget(0);
//See if it is a button-like object (/Ft == /Btn)
if (!w.Contains(PdfName.FT) || !w.Get(PdfName.FT).Equals(PdfName.BTN)) { continue;/*Skipping non-buttons*/ }
//Get the optional field flags, if they don't exist then just use zero
ff = (w.Contains(PdfName.FF) ? w.GetAsNumber(PdfName.FF).IntValue : 0);
if ((ff & ffRadio) == ffRadio) {
//Is Radio
} else if (((ff & ffRadio) != ffRadio) && ((ff & ffPushbutton) != ffPushbutton)) {
//Is Checkbox
} else {
//Regular button
}
}
this.Close();
}
}
}
C# with System.Linq included
for radio buttons , get which option is selected from all the options in radio form, print also all the choice options by their specified name in Adobe Acrobat Pro
AcroFields fields = reader.AcroFields;
List<string> fldNames = new List<string>(fields.Fields.Keys);
if (fldNames.Count > 0) //am gasit cel putin un acroform
{
foreach (string fldname in fldNames)
{
int tip = fields.GetFieldType(fldname);
if (tip == 3) //choice / radio
{
Console.WriteLine("radio form");
string[] valori = fields.GetListSelection(fldname);
foreach (string s in valori)
Console.WriteLine(s + " ");
Console.WriteLine("selected from radio form options");
string[] valori2 = fields.GetAppearanceStates(fldname);
//Console.WriteLine(valori2.Length);
var val2 = (from string c in valori2
where (c.ToLower().CompareTo("off") != 0)
select c).ToList();
if (val2.Count > 0)
foreach (string s2 in val2)
Console.WriteLine(s2 + " ");
}
}
}

The method 'Equals' is not supported

public List<Health_Scheme_System.Employee> GetPenEmployeeTable()
{
Health_Scheme_System.Health_Scheme_SystemDB db = new Health_Scheme_System.Health_Scheme_SystemDB();
var x = (from c in db.Employees
where c.Pensioners.Equals (1)
select c);
return x.ToList();
}
//Selecting multiple columns from an HR view table together with the scheme name of scheme.
public List<EmployeesX> GetPensioners()
{
Health_Scheme_System.Health_Scheme_SystemDB db = new Health_Scheme_System.Health_Scheme_SystemDB();
List<Health_Scheme_System.EmployeeDirectory> listEmployeeView = GetPenEmployeeView();
List<Health_Scheme_System.Employee> listEmployeeTable = GetPenEmployeeTable();
List<Health_Scheme_System.Scheme> listSchemes = GetSchemes();
List<EmployeesX> listOfEmployees = new List<EmployeesX>();
//checking for comparision of getemployeeview to getemployee table and then to getschemes
//Then display the scheme name if they are similar.
for (int i = 0; i < listEmployeeView.Count; i++)
{
EmployeesX emp = new EmployeesX();
emp.ID_NO = listEmployeeView[i].ID_NO;
emp.FIRST_NAME = listEmployeeView[i].FIRST_NAME;
emp.LAST_NAME = listEmployeeView[i].LAST_NAME;
emp.LOCATION_CODE = listEmployeeView[i].LOCATION_CODE;
for (int j = 0; j < listEmployeeTable.Count; j++)
{
if (listEmployeeTable[j].EmployeeIDCard == listEmployeeView[i].ID_NO)
{
emp.Pensioners = listEmployeeTable[j].Pensioners;
for (int k = 0; k < listSchemes.Count; k++)
{
if (listEmployeeTable[j].SchemeID == listSchemes[k].SchemeID)
{
emp.SCHEME_NAME = listSchemes[k].Name;
emp.START_DATE = listEmployeeTable[j].StartSchemeDate;
}
}
}
}
listOfEmployees.Add(emp);
}
return listOfEmployees;
}
How can I make the same method with using .equals??
Have you tried this:
var x = (from c in db.Employees
where c.Pensioners == 1
select c)
Additional info:
If you use a method on an object in a linq query subsonic needs to know how to translate that into pur SQL code. That does not work by default and must be implemented for every known method on every supported type for every dataprovider (if differs from default implementation). So there is a bunch of work to do for subsonic.
A good starting point for knowning what's supported and what not is the TSqlFormatter class. Have a look at protected override Expression VisitMethodCall(MethodCallExpression m)
https://github.com/subsonic/SubSonic-3.0/blob/master/SubSonic.Core/Linq/Structure/TSqlFormatter.cs
There is already an implementation for Equals
else if (m.Method.Name == "Equals")
{
if (m.Method.IsStatic && m.Method.DeclaringType == typeof(object))
{
sb.Append("(");
this.Visit(m.Arguments[0]);
sb.Append(" = ");
this.Visit(m.Arguments[1]);
sb.Append(")");
return m;
}
else if (!m.Method.IsStatic && m.Arguments.Count == 1 && m.Arguments[0].Type == m.Object.Type)
{
sb.Append("(");
this.Visit(m.Object);
sb.Append(" = ");
this.Visit(m.Arguments[0]);
sb.Append(")");
return m;
}
else if (m.Method.IsStatic && m.Method.DeclaringType == typeof(string))
{
//Note: Not sure if this is best solution for fixing side issue with Issue #66
sb.Append("(");
this.Visit(m.Arguments[0]);
sb.Append(" = ");
this.Visit(m.Arguments[1]);
sb.Append(")");
return m;
}
}
I suppose Prnsioners is an integer type so you basically have to add another else if and recomplie subsonic.
This should work but I haven't tested it.
else if (!m.Method.IsStatic && m.Method.DeclaringType == typeof(int))
{
sb.Append("(");
this.Visit(m.Arguments[0]);
sb.Append(" = ");
this.Visit(m.Arguments[1]);
sb.Append(")");
return m;
}
(or you can try the == approach like in the example on the top).

Getting a random UserProfile In SharePoint 2010

I am trying to retrieve a random number of users from the UserProfileManager.
But I am encountering errors when deploying to the live servers. I can't seem to see what is causing the error. My code is below:
for (int i = 0; i < NumberOfUserLimit; i++)
{
UserProfile up = profileManager.GetUserProfile(random.Next(1, NumberOfUserLimit));
if (up["FirstName"] != null && up["FirstName"].Value != null && !String.IsNullOrEmpty(up["FirstName"].Value.ToString()))
{
DataRow drUserProfile;
drUserProfile = dtUserProfile.NewRow();
drUserProfile["DisplayName"] = up.DisplayName;
drUserProfile["FirstName"] = up["FirstName"].Value;
drUserProfile["LastName"] = up["LastName"].Value;
drUserProfile["Department"] = up["Department"].Value;
drUserProfile["Location"] = up["SPS-Location"].Value;
drUserProfile["HireDate"] = up["SPS-HireDate"].Value;
drUserProfile["ContactNumber"] = up["Office"].Value;
if (up["PictureURL"] != null && up["PictureURL"].Value != null && !String.IsNullOrEmpty(up["PictureURL"].Value.ToString()))
{
string cleanAccountName = up["AccountName"].Value.ToString().Replace(#"\", "_");
string pictureUrl = String.Format("https://my.someintranet.com/User Photos/Profile Pictures/{0}_MThumb.jpg", cleanAccountName);
drUserProfile["Image"] = pictureUrl;
}
else
{
drUserProfile["Image"] = "~/_layouts/images/O14_person_placeHolder_96.png";
}
drUserProfile["MySiteUrl"] = up.PublicUrl;
dtUserProfile.Rows.Add(drUserProfile);
}
}
My code works when I apply a simple foreach to my code above instead of the "for loop":
foreach (UserProfile up in profileManager)
Which proves I can return userprofiles.
Any help is appreciated.
profileManager.GetUserProfile(long recordId)
expects a recordId from userprofile table. It is not an index, so you cannot use "random".
If you want to check RecordId, you can take a look at SQL tables of ProfileDB. Table "UserProfile_Full" has MasterRecordId column. Your parameter in GetUserProfile has to match of the user profile's MasterRecordId.
you can use the following code to get your random profiles:
IEnumerator profiles = profileManager.GetEnumerator();
int index = new Random().Next(1, 100);
while (index >= 0 && profiles.MoveNext())
index--;
UserProfile currentProfile = (UserProfile)profiles.Current
Code that handles Random better
public class TestClass
{
private random = new Random();
private long totalNumberOfProfiles; //ProfileManager.Count not always returns count correctly
public TestClass()
{
//this does not have to be in constructor but point is to have it cached (reasonably)
IEnumerator profiles = profileManager.GetEnumerator();
long counter = 0;
while (profiles.MoveNext())
counter++;
this.totalNumberOfProfiles = counter;
}
public fillInDataSet()
{
//something is here...
IEnumerator profiles = profileManager.GetEnumerator();
int index = random.Next(1, totalNumberOfProfiles);
while (index >= 0 && profiles.MoveNext())
index--;
UserProfile currentProfile = (UserProfile)profiles.Current
//something is here...
}
}

Resources