Here is my case I have custom control that inherent from UILable
and I need to create method that take image (from code or storyboard)
to be added to my label
My tries to convert this code to Xamarin.iOS Source
let attachment = NSTextAttachment()
attachment.image = UIImage(named: "yourIcon.png")
let attachmentString = NSAttributedString(attachment: attachment)
let myString = NSMutableAttributedString(string: price)
myString.appendAttributedString(attachmentString)
label.attributedText = myString
public void SetLeftDrawable(UIImage image){
var attachment = new NSTextAttachment();
attachment.Image = image;
var attachmentString = new
NSAttributedString(attachment,null); // this method take string not NSTextAttachment
}
any one could help me
Try this:
public void SetLeftDrawable (UIImage image)
{
var attachment = new NSTextAttachment ();
attachment.Image = image;
var attachmentString = NSAttributedString.FromAttachment (attachment);
//replace "price" with your string.
var myString = new NSMutableAttributedString ("price");
myString.Append (attachmentString);
AttributedText = myString;
}
Hope this helps.-
Related
i am tried to find the link wall face,but when i use the reference to create a new dimension , i will get result about 'invaild number of references'. i cant trans link face to active face.
public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
{
UIDocument uidoc = commandData.Application.ActiveUIDocument;
Document doc = uidoc.Document;
var rf1 = uidoc.Selection.PickObject(ObjectType.PointOnElement, "select");
var element1 = doc.GetElement(rf1);
var location = element1.Location as LocationPoint;
var point = location.Point;
var rf2 = uidoc.Selection.PickObject(ObjectType.LinkedElement, "select");
var linkElement = doc.GetElement(rf2) as RevitLinkInstance;
var linkDoc = linkElement.GetLinkDocument();
var linkWall = linkDoc.GetElement(rf2.LinkedElementId) as Wall;
var wallLocation = linkWall.Location as LocationCurve;
var curve = wallLocation.Curve;
var cRf = curve.Reference;
var solid = BIMTools.Geometry.GetSolid(linkWall);
Face face = null;
foreach (var solidFace in solid.Faces)
{
XYZ normal = ((Face)solidFace).ComputeNormal(new UV(0, 0));
if (normal.Y < 0)
{
face = solidFace as Face;
break;
}
}
var viewLevel = uidoc.ActiveView.GenLevel.Elevation;
var tPoint = new XYZ(point.X,(face as PlanarFace).Origin.Y, viewLevel);
point = new XYZ(point.X, point.Y, viewLevel);
var line = Line.CreateBound(point, tPoint);
var references = new ReferenceArray();
references.Append(rf1);
references.Append(face.Reference);
using (Transaction trans = new Transaction(doc,"create"))
{
trans.Start();
var dimension = doc.Create.NewDimension(uidoc.ActiveView, line, references);
trans.Commit();
}
return Result.Succeeded;
}
The Building Coder provides a whole list of articles on creating dimensioning.
New to MVC and having some trouble with what should be simple. I'm trying to return a dataset to just an Excel spreadsheet without any real UI.
Here's my code (cannibalized from a few sources):
Controller code:
public ActionResult GetCommissionsExcel(string agencyid, string month, string year)
{
try
{
var as400rep = new iSeriesRepository(new iSeriesContext());
var results = as400rep.GetCommissionExcel(agencyid, month, year);
string xml = String.Empty;
XmlDocument xmlDoc = new XmlDocument();
XmlSerializer xmlSerializer = new XmlSerializer(results.GetType());
using (System.IO.MemoryStream xmlStream = new System.IO.MemoryStream())
{
xmlSerializer.Serialize(xmlStream, results);
xmlStream.Position = 0;
xmlDoc.Load(xmlStream);
xml = xmlDoc.InnerXml;
}
var fName = string.Format("CommissionsExcelExport-{0}", DateTime.Now.ToString("s"));
byte[] fileContents = System.Text.Encoding.UTF8.GetBytes(xml);
return File(fileContents, "application/vnd.ms-excel", fName);
}
catch (Exception ex)
{
Log.Error(ex.Message, ex.InnerException);
throw;
}
}
The jQuery call:
function getExcelExport() {
var activePane = $('div.tab-pane.active');
var agencyCompany = $(activePane).find('#Agency_AgencyId').val();
var month = $(activePane).find('#CommissionMonth').val();
var year = $(activePane).find('#CommissionYear').val();
var url = '#Url.Content("~")' + 'AgencyManagement/GetCommissionsExcel';
window.location = 'AgencyManagement/GetCommissionsExcel';
//$.post('#Url.Action("GetCommissionsExcel", "AgencyManagement")' , {agencyid: agencyCompany, month: month, year: year});
};
It pulls back the data, but I can't figure out how to get it to pop from the search window. It looks like the window.location line makes the call, but I need to post the parameters to the call and that's where I'm stuck.
Figured it out. Just needed to call the jQuery as follows:
window.location = 'AgencyManagement/GetCommissionsExcel?agencyID=' + agencyCompany + '&month=' + month + '&year=' + year;
And I needed to append ".xls" to the filename in the controller action.
var fName = string.Format("CommissionsExcelExport-{0}", DateTime.Now.ToString("s"));
fName = fName + ".xls";
Worked like a charm
I want to send DataSet data with email excel file attachment in C# but I don't want to create Excel file physically. It can be do with MemoryStream but I couldn't.
Another problem I want to set Excel file's encoding type because data may be Russian or Turkish special character.
Please help me...
Here is my sample code...
<!-- language: c# -->
var response = HttpContext.Response;
response.Clear();
response.Charset = "utf-8";
response.ContentEncoding = System.Text.Encoding.Default;
GridView excelGridView = new GridView();
excelGridView.DataSource = InfoDataSet;
excelGridView.DataBind();
excelStringWriter = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(excelStringWriter);
excelGridView.RenderControl(htw);
byte[] ExcelData = emailEncoding.GetBytes(excelStringWriter.ToString());
MemoryStream ms = new MemoryStream(ExcelData);
mailMessage.Attachments.Add(new Attachment(ms, excelFileName, "application/ms-excel"));
<!-- language: c# -->
here is another one simple and easy with excel attchment
public string SendMail(string LastId)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
SqlCommand cmd = new SqlCommand("sp_GetMailData", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#LastID", LastId);
con.Open();
string result = "0";
string temptext = "";
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt=new DataTable();
da.Fill(dt);
//ExportToSpreadsheet(dt,"My sheet");
GridView gv = new GridView();
gv.DataSource = dt;
gv.DataBind();
AttachandSend(gv);
con.Close();
return result.ToString();
}
public void AttachandSend(GridView gv)
{
StringWriter stw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(stw);
gv.RenderControl(hw);
System.Text.Encoding Enc = System.Text.Encoding.ASCII;
byte[] mBArray = Enc.GetBytes(stw.ToString());
System.IO.MemoryStream mAtt = new System.IO.MemoryStream(mBArray, false);
System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage();
MailAddress address = new
MailAddress("xxxxxxxxxxxxx", "Admin");
mailMessage.Attachments.Add(new Attachment(mAtt, "sales.xls"));
mailMessage.Body = "Hi PFA";
mailMessage.From = address;
mailMessage.To.Add("xxxxxxxxxxxx");
mailMessage.Subject = "xxxxxxxxxxxxxx";
mailMessage.IsBodyHtml = true;
var smtp = new SmtpClient();
smtp.Send(mailMessage);
}
Here is your solution
private static Stream DataTableToStream(DataTable table)
{
const string semiColon = ";";
var ms = new MemoryStream();
var sw = new StreamWriter(ms);
foreach (DataColumn column in table.Columns)
{
sw.Write(column.ColumnName);
sw.Write(semiColon);
}
sw.Write(Environment.NewLine);
foreach (DataRow row in table.Rows)
{
for (int i = 0; i < table.Columns.Count; i++)
{
sw.Write(row[i].ToString().Replace(semiColon, string.Empty));
sw.Write(semiColon);
}
sw.Write(Environment.NewLine);
}
return ms;
}
private static MailMessage CreateMail(string from,
string to,
string subject,
string body,
string attname,
Stream tableStream)
{
// using System.Net.Mail
var mailMsg = new MailMessage(from, to, subject, body);
tableStream.Position = 0;
mailMsg.Attachments.Add(
new Attachment(tableStream, attname, CsvContentType));
return mailMsg;
}
private const string CsvContentType = "application/ms-excel";
private static void ExportToSpreadsheetInternal(Stream tableStream, string name)
{
HttpContext context = HttpContext.Current;
context.Response.Clear();
context.Response.ContentType = CsvContentType;
context.Response.AppendHeader(
"Content-Disposition"
, "attachment; filename=" + name + ".xls");
tableStream.Position = 0;
tableStream.CopyTo(context.Response.OutputStream);
context.Response.End();
}
public static void ExportToSpreadsheet(DataTable table, string name)
{
var stream = DataTableToStream(table);
var mailMsg = CreateMail("from#ddd.com",
"to#ddd.com",
"spread",
"the spread",
name,
stream);
//ExportToSpreadsheetInternal(stream, name);
// send the mailMsg with SmtpClient (config in your web.config)
var smtp = new SmtpClient();
smtp.Send(mailMsg);
}
Call this method
ExportToSpreadsheet(DataTable table, string name)
I am using Rotativa to generate PDF in my "MVC" application. How can I save Rotativa PDF? I need to save the document on a server after all the process is completed.
Code below:
public ActionResult PRVRequestPdf(string refnum,string emid)
{
var prv = functions.getprvrequest(refnum, emid);
return View(prv);
}
public ActionResult PDFPRVRequest()
{
var prv = Session["PRV"] as PRVRequestModel;
byte[] pdfByteArray = Rotativa.WkhtmltopdfDriver.ConvertHtml("Rotativa", "Approver", "PRVRequestPdf");
return new Rotativa.ViewAsPdf("PRVRequestPdf", new { refnum = prv.rheader.request.Referenceno });
}
You can give this a try
var actionResult = new ActionAsPdf("PRVRequestPdf", new { refnum = prv.rheader.request.Referenceno, emid = "Whatever this is" });
var byteArray = actionResult.BuildPdf(ControllerContext);
var fileStream = new FileStream(fullPath, FileMode.Create, FileAccess.Write);
fileStream.Write(byteArray, 0, byteArray.Length);
fileStream.Close();
If that doesn't do the trick then, you can follow the answers here
Just make sure if you do it this way not to have PRVRequestPdf return as a PDF View, rather a normal View like you have above (only mention as managed to fall foul of that myself causing lots of fun).
Another useful answer:
I found the solution here
var actionPDF = new Rotativa.ActionAsPdf("YOUR_ACTION_Method", new { id = ID, lang = strLang } //some route values)
{
//FileName = "TestView.pdf",
PageSize = Size.A4,
PageOrientation = Rotativa.Options.Orientation.Landscape,
PageMargins = { Left = 1, Right = 1 }
};
byte[] applicationPDFData = actionPDF.BuildPdf(ControllerContext);
This is the original thread
You can achieve this with ViewAsPdf.
[HttpGet]
public ActionResult SaveAsPdf(string refnum, string emid)
{
try
{
var prv = functions.getprvrequest(refnum, emid);
ViewAsPdf pdf = new Rotativa.ViewAsPdf("PRVRequestPdf", prv)
{
FileName = "Test.pdf",
CustomSwitches = "--page-offset 0 --footer-center [page] --footer-font-size 8"
};
byte[] pdfData = pdf.BuildFile(ControllerContext);
string fullPath = #"\\server\network\path\pdfs\" + pdf.FileName;
using (var fileStream = new FileStream(fullPath, FileMode.Create, FileAccess.Write))
{
fileStream.Write(pdfData, 0, pdfData.Length);
}
return Json(new { isSuccessful = true }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
//TODO: ADD LOGGING
return Json(new { isSuccessful = false, error = "Uh oh!" }, JsonRequestBehavior.AllowGet);
//throw;
}
}
You can simply try this:
var fileName = string.Format("my_file_{0}.pdf", id);
var path = Server.MapPath("~/App_Data/" + fileName);
System.IO.File.WriteAllBytes(path, pdfByteArray );
So I've run into an interesting problem. I need to specify a custom WHERE clause in a PowerPivot query. I must change it based on external conditions. I would like to edit the file and save a copy. Any idea how to do this? I opened the PowerPivot file from binary, but it appears encrypted...
You can go to existing connections, and then make an update there. If you open the same data source (SQL, SSRS, or anything else) again instead of changing parameters on the existing connection, it will slow your perf as PowerPivot will treat those as separate connections.
Solution was to open the Excel workbook up as a Zip (using the Package class).
If you are looking to modify the queries, you can. The file at /xl/customData/item1.data is a backup file that represents the PowerPivot database (which is just an Analysis Services database running in Vertipaq mode) used to process queries. You need to restore the file to a SSAS instance running in Vertipaq mode. Once that's done, script the queries as an ALTER script. Modify the scripts (in this case, replacing #projectId with my actual projectID), then run them against the database. Once all this is done, back the database up and put back into the Excel workbook. That modifies the queries.
The connection data is stored in the /xl/connections.xml file. Open that up, modify, and replace. Repack it all up again, and now you have a workbook again.
Here's the code I made. You will have to call the methods as you need. Basic idea is there, though...
const string DBName = "Testing";
const string OriginalBackupPath = #"\\MyLocation\BKUP.abf";
const string ModifiedBackupPath = #"\\MyLocation\BKUPAfter.abf";
const string ServerPath = #"machineName\powerpivot";
private static readonly Server srv = new Server();
private static readonly Scripter scripter = new Scripter();
private static Database db;
private static byte[] GetPackagePartContents(string packagePath, string partPath)
{
var pack = Package.Open(packagePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
var part = pack.GetPart(new Uri(partPath, UriKind.Relative));
var stream = part.GetStream();
var b = new byte[stream.Length];
stream.Read(b, 0, b.Length);
stream.Flush();
stream.Close();
pack.Flush();
pack.Close();
return b;
}
private static void WritePackagePartContents(string packagePath, string partPath, byte[] contents)
{
var uri = new Uri(partPath, UriKind.Relative);
var pack = Package.Open(packagePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
var part = pack.GetPart(uri);
var type = part.ContentType;
pack.DeletePart(uri);
pack.CreatePart(uri, type);
part = pack.GetPart(uri);
var stream = part.GetStream();
stream.Write(contents, 0, contents.Length);
stream.Flush();
stream.Close();
pack.Flush();
pack.Close();
}
private static void RestoreBackup(string server, string dbName, string backupPath)
{
srv.Connect(server);
if (srv.Databases.FindByName(dbName) != null) { srv.Databases.FindByName(dbName).Drop(); srv.Update(); }
srv.Restore(backupPath, dbName, true);
srv.Update();
srv.Refresh();
}
private static void WriteContentsToFile(byte[] contents, string filePath)
{
var fileStream = File.Open(filePath, FileMode.OpenOrCreate, FileAccess.Write);
fileStream.Write(contents, 0, contents.Length);
fileStream.Flush();
fileStream.Close();
}
private static byte[] ReadContentsFromFile(string filePath)
{
var fileStream = File.Open(filePath, FileMode.OpenOrCreate, FileAccess.Write);
var b = new byte[fileStream.Length];
fileStream.Read(b, 0, b.Length);
fileStream.Flush();
fileStream.Close();
return b;
}
private static XDocument GetAlterScript(MajorObject obj)
{
var stream = new MemoryStream();
var streamWriter = XmlWriter.Create(stream);
scripter.ScriptAlter(new[] { obj }, streamWriter, false);
streamWriter.Flush();
streamWriter.Close();
stream.Flush();
stream.Position = 0;
var b = new byte[stream.Length];
stream.Read(b, 0, b.Length);
var alterString = new string(Encoding.UTF8.GetString(b).ToCharArray().Where(w => w != 65279).ToArray());
var alter = XDocument.Parse(alterString);
stream.Close();
return alter;
}
private static void ExecuteScript(string script)
{
srv.Execute(script);
srv.Update();
db.Process();
db.Refresh();
}
private static void ProcessPowerpointQueries(string bookUrl, string projectId)
{
byte[] b = GetPackagePartContents(bookUrl, "/xl/customData/item1.data");
WriteContentsToFile(b, OriginalBackupPath);
RestoreBackup(ServerPath, DBName, OriginalBackupPath);
var db = srv.Databases.GetByName(DBName);
var databaseView = db.DataSourceViews.FindByName("Sandbox");
var databaseViewAlter = GetAlterScript(databaseView);
var cube = db.Cubes.FindByName("Sandbox");
var measureGroup = cube.MeasureGroups.FindByName("Query");
var partition = measureGroup.Partitions.FindByName("Query");
var partitionAlter = GetAlterScript(partition);
var regex = new Regex(#"\s#projectid=\w*[ ,]");
var newDatabaseViewAlter = databaseViewAlter.ToString().Replace(regex.Match(databaseViewAlter.ToString()).Value.Trim(',',' '), #"#projectid=" + projectId);
ExecuteScript(newDatabaseViewAlter);
var newPartitionAlter = partitionAlter.ToString().Replace(regex.Match(partitionAlter.ToString()).Value.Trim(',', ' '), #"#projectid=" + projectId);
ExecuteScript(newPartitionAlter);
db.Backup(ModifiedBackupPath, true);
WritePackagePartContents(bookUrl, #"/xl/customData/item1.data", ReadContentsFromFile(ModifiedBackupPath));
db.Drop();
srv.Disconnect();
}
private static void ProcessWorkbookLinks(string bookUrl, string newCoreUrl)
{
var connectionsFile = GetPackagePartContents(bookUrl, #"/xl/connections.xml");
var connectionsXml = Encoding.UTF8.GetString(connectionsFile);
connectionsXml = connectionsXml.Replace(
new Regex(#"Data Source=\S*;").Match(connectionsXml).Value.Trim(';'), #"Data Source=" + newCoreUrl);
WritePackagePartContents(bookUrl, #"/xl/connections.xml", connectionsXml.Replace(#"https://server/site/", newCoreUrl).ToCharArray().Select(Convert.ToByte).ToArray());
}