Loading ACIS file in solidworks with c# API - c#

J'essaie d'automatiser le chargement de fichier SAT dans SolidWorks en faisant un Add-in.
pour cela j'utilise LoadFile4
swPart = (PartDoc)mSldWorksApplication.LoadFile4(fileNameToWorkOn,"r", ImportData, ref m_LongStatus);
Je n'arrive pas à lire le fichier (m_LongStatus=1)
voici une partie de mon code
foreach (var file in ListOfFiles)
{
if (file.EntityName.ToUpper().Contains(".SAT"))
{
using (Stream rStream = zipFileSystem.OpenFile(file, FileAccess.Read))
{
string fileNameToWorkOn = "d:\\temp\\" + file.EntityName;
var wfileStream = File.Create(fileNameToWorkOn);
rStream.CopyTo(wfileStream);
// work with the physical tempory files to import it in SolidWorks
//Import SAT file
ImportData = (Import3DInterconnectData)mSldWorksApplication.GetImportFileData(fileNameToWorkOn);
string fileNameToCreate = fileNameToWorkOn.ToUpper().Replace(".SAT", ".SLDPRT");
ModelDoc2 swModel = mSldWorksApplication.OpenDoc6(fileNameToCreate, (int)swDocumentTypes_e.swDocPART, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", 0, 0);
swPart = (PartDoc)mSldWorksApplication.LoadFile4(fileNameToWorkOn,"r", ImportData, ref m_LongStatus);
swModel = (ModelDoc2)swPart;
//Close the model
mSldWorksApplication.CloseDoc(fileNameToCreate);
wfileStream.Close();
// delete now the physical tempory files
File.Delete(fileNameToWorkOn);
}
}
}
quelqu'un a t-il déjà eu ce problème ?

Related

Split string by ". " except when after a number

I want to split strings, by phrases, and to do that I'm doing this:
string.Split(new[] { ". ", "? ", "! " }, StringSplitOptions.None);
The thing is my string sometimes catch that after a number, when it has different points, and I want to separate by before the number, and not after, if it is possible.
original:
Com um processo de agendamento de não mais que 60 segundos, um
pagamento seguro, garantia de qualidade, a Wegho torna-se o meio mais
simples e conveniente de poder agendar serviços para o seu lar.
Entenda-se lar como a simbiose perfeita do ativo físico “casa” e do
ativo “emocional” família. Preparado para ter um parceiro de
excelência nos serviços que precisa para o seu lar? 1. Explore os
nossos serviços em Wegho.om 2. Selecione o serviço que pretende.
Através do código postal verificaremos se estamos presentes na área
que pretende 3. Escolha uma hora
result:
Com um processo de agendamento de não mais que 60 segundos, um
pagamento seguro, garantia de qualidade, a Wegho torna-se o meio mais
simples e conveniente de poder agendar serviços para o seu lar.
Entenda-se lar como a simbiose perfeita do ativo físico “casa” e do
ativo “emocional” família.
Preparado para ter um parceiro de excelência nos serviços que precisa
para o seu lar?
Explore os nossos serviços em Wegho.om
Selecione o serviço que pretende. Através do código postal verificaremos se estamos presentes na área que pretende
Escolha uma hora
And also, is it possible to keep the caught separating characters from which the string was split in the strings?
One approach is to split strings the way you do currently, and then go through the resultant list again, re-combining number-only strings with strings that immediately follow them:
var tokens = string.Split(new[] { ". ", "? ", "! " }, StringSplitOptions.None);
var res = new List<string>();
for (int i = 0 ; i < tokens.Length ; i++) {
var tok = tokens[i];
int ignore;
if (i != tokens.Length-1 && int.TryParse(tok, out ignore)) {
tok += ". "+tokens[++i];
}
res.Add(tok);
}
Note that your overall approach is fragile, because it is not possible to tell if a numeric part is a "bullet number" or not without some user mark-up to help you identify numbered bullets.
You could try regular expressions:
string pattern = #"([^\d][.!?][ ])";
string substitution = #"$1\n\n";
string input = #"Com um processo de agendamento de não mais que 60 segundos, um pagamento seguro, garantia de qualidade, a Wegho torna-se o meio mais simples e conveniente de poder agendar serviços para o seu lar. Entenda-se lar como a simbiose perfeita do ativo físico “casa” e do ativo “emocional” família. Preparado para ter um parceiro de excelência nos serviços que precisa para o seu lar? 1. Explore os nossos serviços em Wegho.om. 2. Selecione o serviço que pretende. Através do código postal verificaremos se estamos presentes na área que pretende. 3. Escolha uma hora";
RegexOptions options = RegexOptions.IgnoreCase;
Regex regex = new Regex(pattern, options);
string result = regex.Replace(input, substitution);
Check the full code and result.
However, the split will work inside the bullets also. And you will need to end your bullet content with a dot also.

How To Execute GenericHandler Method in C# WebService

I have to upload images to MySQL database, im using html, ajax, javascript and c#. I have 2 codes, 1 to upload the path of the image and the other upload the image in blop field, both work fine, but im using WebService and for the file upload Im using GenericHandler, my question is, How can I execute my methods but in my WebService?
Code of the GenericHandler:
public void ProcessRequest (HttpContext context)
{
string sql = "";
string ruta = "";
int files = 0;
//IF para comprobar que el total de archivos cargados sea mayor a 0
if (context.Request.Files.Count > 0)
{
//Variable que almacenara todos los archivos a cargar
HttpFileCollection SelectedFiles = context.Request.Files;
//Ciclor for para recorrer el arreglo y darle un indice a todos los archivos
for (int i = 0; i < SelectedFiles.Count; i++)
{
// Variable que tomara el valor dado por el for
HttpPostedFile PostedFile = SelectedFiles[i];
//Variable que tomar el valor de la ruta y el nombre del archivo que se guardara
string FileName = context.Server.MapPath("~/Uploads/" + PostedFile.FileName);
// Metodo para guardar el archivo
files++;
PostedFile.SaveAs(FileName);
ruta = FileName;
if (files == SelectedFiles.Count)
sql += ruta;
else
sql += ruta + '|';
}
FileUpload fu = new FileUpload(sql);
conn.Foto(fu, 1);//hjjiijj.mnbfgytrvgfdhghhygd
}
// Else para mandar mensaje de error.
else
{
context.Response.ContentType = "text/plain";
context.Response.Write("Please Select Files");
}
//Mensaje al realizar el metodo satisfactoriamente
context.Response.ContentType = "text/plain";
context.Response.Write("Files Uploaded Successfully!!");
}
Use ajax, and in the url you call your generichandler.

ListView only gets first row of .csv file

I have an excel table with multiple rows, and when I import my .csv file it only displays the first row.
What I want is to fill the list with every row.
cargarCSV() = load .csv file
validar() = pass the csv file to the listview
private void cargarCSV() //Load .csv
{
OpenFileDialog dialogoCargar = new OpenFileDialog();
dialogoCargar.Filter = "Archivos CSV|*.csv";
dialogoCargar.FilterIndex = 1;
if(dialogoCargar.ShowDialog() == DialogResult.OK)
{
filepath = dialogoCargar.FileName;
txtbox_ArchivoCargado.Text = filepath;
}
}
private void Validar() //Pass .csv to ListView
{
empleadosValido = true;
try {
FileStream fileStreamNew = File.Open(filepath, FileMode.Open, FileAccess.ReadWrite);
StreamReader streamRead = new StreamReader(fileStreamNew);
string strView = streamRead.ReadToEnd();
streamRead.Close();
fileStreamNew.Close();
String[] strArray = strView.Split(new char[] { ',' });
ListViewItem item = new ListViewItem(strArray[0].ToString());
item.SubItems.Add(strArray[1].ToString());
item.SubItems.Add(strArray[2].ToString());
item.SubItems.Add(strArray[3].ToString());
item.SubItems.Add(strArray[4].ToString());
item.SubItems.Add(strArray[5].ToString());
item.SubItems.Add(strArray[6].ToString());
list_Previ.Items.Add(item);
}catch (Exception ex)
{
if (ex is IOException)
{
MessageBox.Show("El archivo se encuentra en uso por otro programa\nPor favor cierra otros programas e intenta de nuevo.", "Corporativo Acosta | Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
empleadosError = true;
MessageBox.Show(ex.ToString());
}
if (ex is IndexOutOfRangeException)
{
MessageBox.Show("Hay un problema con tus columnas.\nVerifica que correspondan las columnas a importar\ncon las de la tabla (7 columnas)", "Corporativo Acosta | Error", MessageBoxButtons.OK ,MessageBoxIcon.Error);
empleadosError = true;
MessageBox.Show(ex.ToString());
}
}
}
Without changing too much of your actual code, but insering a loop for each line present in your file you should go for
foreach(string strView = File.ReadLines(filepath))
{
String[] strArray = strView.Split(new char[] { ',' });
ListViewItem item = new ListViewItem(strArray[0].ToString());
item.SubItems.Add(strArray[1].ToString());
item.SubItems.Add(strArray[2].ToString());
item.SubItems.Add(strArray[3].ToString());
item.SubItems.Add(strArray[4].ToString());
item.SubItems.Add(strArray[5].ToString());
item.SubItems.Add(strArray[6].ToString());
list_Previ.Items.Add(item);
}
Of course you could remove all of your references to the FileStream and StreamReader variables.
Also, if you forecast that some of your lines contains less than 7 elements, I suggest to add a check for the array length just before adding the element to the ListView Items collection and do not rely on exception handling to continue. Using exceptions to drive your code is a bad practice and hitting an exception is costly in terms of performance ( a lot more than putting an if before adding the elements), so something like this should considered
if(strArray.Length > 1) item.SubItems.Add(strArray[1].ToString());
if(strArray.Length > 2) item.SubItems.Add(strArray[2].ToString());
....

the current index is out of range c#

I've the below c# code and i'm getting the current index is out of range error
public partial class FrmTreeViewContinents : Form
{
// Objets communs
XmlDocument monXml = new XmlDocument();
XmlNodeList listeNode = null;
XmlNode root = null;
public FrmTreeViewContinents()
{
InitializeComponent();
}
private void btnTransferToXml_Click(object sender, EventArgs e)
{
ManipXml obj = new ManipXml();
// Sérialise une collection d'objets 'Pays' en fichier XML
obj.SerialiseObjets("Pays.xml");
}
private void btnAfficheEntity_Click(object sender, EventArgs e)
{
// Chargement du fichier XML - Abandon si erreur
if (!ChargeFichierXml()) return;
// Sélecton des données dans le noeud XML 'Pays'
listeNode = root.SelectNodes("//Pays");
// Affichage des données lues
AffichageDonnees();
}
// Méthode d'affichage des données lues dans le fichier XML
private void AffichageDonnees()
{
txtBoxAffiche.Clear();
foreach (XmlNode noeud in listeNode)
{
txtBoxAffiche.Text += noeud.Attributes[2].InnerText.ToString() +
" - " +
noeud.Attributes[3].InnerText.ToString() +
" - " +
noeud.Attributes[4].InnerText.ToString() +
Environment.NewLine;
}
}
// Méthode de chargement du fichier XML
private bool ChargeFichierXml()
{
try
{
monXml.Load("Pays.xml");
}
catch (Exception ex)
{
MessageBox.Show("Erreur sur chargement du fichier XML"
+ Environment.NewLine + ex.Message,
"Erreur",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
return false;
}
//XmlNodeList listeNode;
root = monXml.DocumentElement;
return true;
}
}
class ManipXml
{
// Cette méthode permet de générer un fichier XML avec une collection de 'Pays'
public void SerialiseObjets(string sNomFichierXml)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Collection<Pays>));
Collection<Pays> colPays = new Collection<Pays>();
Pays cnt1 = new Pays();
cnt1.NomPays = "Australie";
cnt1.NomCapitalePays = "Canberra";
cnt1.NomContinent = "Australie";
Pays cnt2 = new Pays();
cnt2.NomPays = "France";
cnt2.NomCapitalePays = "Paris";
cnt2.NomContinent = "Europe";
Pays cnt3 = new Pays();
cnt3.NomPays = "Espagne";
cnt3.NomCapitalePays = "Madrid";
cnt3.NomContinent = "Europe";
Pays cnt4 = new Pays();
cnt4.NomPays = "Chine";
cnt4.NomCapitalePays = "Beijing";
cnt4.NomContinent = "Asie";
Pays cnt5 = new Pays();
cnt5.NomPays = "Malaysia";
cnt5.NomCapitalePays = "Kuala-Lumpur";
cnt5.NomContinent = "Asie";
// Ajout des 'Continent' dans la collection
colPays.Add(cnt1);
colPays.Add(cnt2);
colPays.Add(cnt3);
colPays.Add(cnt4);
colPays.Add(cnt5);
// Instanciation d'un Stream
Stream st = new FileStream(sNomFichierXml, FileMode.Create);
// Génération du fichier XML
xmlSerializer.Serialize(st, colPays);
st.Close();
}
}
public class Pays // Définition de la classe Continent
{
public string NomPays { get; set; }
public string NomCapitalePays { get; set; }
public string NomContinent { get; set; }
}
the error i got is in the section below , which is "the current index is out of range"
foreach (XmlNode noeud in listeNode){
txtBoxAffiche.Text += noeud.Attributes[2].InnerText.ToString() +" - "
+ noeud.Attributes[3].InnerText.ToString() + " - "
+ noeud.Attributes[4].InnerText.ToString() +
Environment.NewLine;
}
can you please help me
thank you
Problem : You might be accessing the invalid Attributes of the Pays.xml file.
Solution: You need to check the Attributes.Count property before accessing the Attributes of the Pays.xml file.
Try This:
foreach (XmlNode noeud in listeNode)
{
for(int i=2;i<noeud.Attributes.Count;i++)
{
if(i!=noeud.Attributes.Count-1)
txtBoxAffiche.Text += noeud.Attributes[i].InnerText.ToString() +" - ";
else
txtBoxAffiche.Text += noeud.Attributes[i].InnerText.ToString() + Environment.NewLine;
}
}
The error is due to you are using the Index out of range.
for example if Array size 3 but if you try to access 4th index ,it will give error.
so please check this part for index value
foreach (XmlNode noeud in listeNode){
txtBoxAffiche.Text += noeud.Attributes[2].InnerText.ToString() +" - "
+ noeud.Attributes[3].InnerText.ToString() + " - "
+ noeud.Attributes[4].InnerText.ToString() +
Environment.NewLine;
}
The problem is in one of the Attributes[] index. You get the position 2, 3 and 4, and I bet that you don't have that many Attributes (4, 3 or 2).
You can set that values first to some variables before using them.
string attribute2 = noeud.Attributes[2].InnerText.ToString();
string attribute3 = noeud.Attributes[3].InnerText.ToString();
string attribute4 = noeud.Attributes[4].InnerText.ToString();
But this isn't a very good practice.... You would check first if the attribute exists.
string attribute2;
if (noeud.Attributes[2] != null) {
attribute2 = noeud.Attributes[2].InnerText.ToString();
}

Regex, I need to improve a method to get src and alt from an image

There is no problem to get the src or alt separately,but how can get both at the same time every one with a group name.
We have to bear in mind that alt can be to the left or right of src.
I am in a hurry, so I found a quick solution, creating 3 groupnames for the src, and and for alt. I know we can do it a lot better.
private void GetFirstImage(string newHtml, out string imgstring, out string imgalt)
{
imgalt = "";
imgstring = "";
string pattern = "(?<=<img(?<name1>\\s+[^>]*?)src=(?<q>['\"]))(?<url>.+?)(?=\\k<q>)(?<name2>.+?)\\s*\\>";
try
{
//si hay imagen
if (Regex.IsMatch(newHtml, pattern))
{
Regex r = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
imgstring = r.Match(newHtml).Result("${url}");
string tempalt = "", tempalt2;
tempalt = r.Match(newHtml).Result("${name1}");
tempalt2 = r.Match(newHtml).Result("${name2}");
//ya tenemos la ruta de la imagen y de lo que aparece a izq y a derecha dentro de <img>
try
{
pattern = "alt=(?<q>['\"])(?<alt>.+?)(?=\\k<q>)";
//si hay algo que no sea vacío a la izquierda de la ruta
if(!String.IsNullOrEmpty(tempalt.Trim()))
{
r = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
//si cumple con el pattern para buscar el alt
if (Regex.IsMatch(tempalt, pattern))
{
imgalt = r.Match(tempalt).Result("${alt}");
}
}
//si no se encontró el alt y hay algo a la derecha
if(String.IsNullOrEmpty(imgalt) && !String.IsNullOrEmpty(tempalt2.Trim()))
{
r = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
//si se cumple el patrón del alt
if (Regex.IsMatch(tempalt2, pattern))
{
imgalt = r.Match(tempalt2).Result("${alt}");
}
}
}
catch{ }
}
}
catch{}
}
Simple... don't use Regex. Use a DOM parser - so XmlDocument for xhtml or the HTML Agility Pack for (non-x)html.
Then just query root.SelectNodes("//img") and look at the "src" and "alt" attributes on each element (i.e. node.Attributes["src"].Value, etc)
Regex is NOT a good tool for parsing html (since it is not a regular language).

Categories

Resources